void main(){
Info* info;
inserir(info);
//O erro acontece na linha de baixo, como se o
//que foi feito na função inserir não persistiu de fato
//na estrutura
printf("%d\n", info->val);
}
What happens here is that the info variable does not change its value before and after the inserir()
function.
The initial value of the variable (garbage because it was not initialized) is the value that will be used in printf.
As you suggest in your answer, you can solve by assigning a value before calling the function; or instead of passing the value you pass the address.
int main(void) {
Info *info;
inserir(&info);
printf("%d\n", info->val);
free(info);
}
void inserir(Info **x) {
*x = malloc(sizeof **x); // falta validacao
(*x)->val = 10;
}
Still another solution is to use the return value of the function
int main(void) {
Info *info;
info = criarinfo();
printf("%d\n", info->val);
free(info);
}
Info *criarinfo(void) {
Info *x;
x = malloc(sizeof *x); // falta validacao
x->val = 10;
return x;
}
In my opinion, your solution is the best!
Notice that in the two solutions above, malloc
and free
are in different places. It becomes much easier to manage memory when the function that makes malloc
'is responsible for also doing free
.