Targeting failure when changing a Struct value in C

1

A Falha de segmentação error is occurring when trying to access information from a struct. The code is as follows

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int val;
}Info;

void inserir(Info*);

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);

}

void inserir(Info* info){
    info = (Info *)malloc(sizeof(Info));
    info->val=10;
}
    
asked by anonymous 11.04.2015 / 08:32

2 answers

3
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 .

    
11.04.2015 / 09:53
1

The solution to this problem was to change the location of malloc

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int val;
}Info;

void inserir(Info*);

void main(){
    //A mudança está aqui
    Info* info = (Info *)malloc(sizeof(Info));
    inserir(info);

    printf("%d\n", info->val);
    free(info);

}

void inserir(Info* info){
    info->val=10;
}

So I understand I was passing an empty structure pointer with no memory address to the inserir function. If I am wrong please comment.

    
11.04.2015 / 08:32