1

When I try to update a pointer inside a struct, I get Segmentation fault when excuting the update function, I don't get the error when executing the print function.

Any help would be appreciated.

Here is the code:

// the struct interpretation contains a dynamic array of variables(boolean values) ex : variables[i] is the value of the variable(i+1)
typedef struct {
    bool * variables;
    int number_of_var;
} INTERPRETATION;

INTERPRETATION * INTERPRETATION_create();
void INTERPRETATION_update(INTERPRETATION *,int,bool);
void INTERPRETATION_print(INTERPRETATION);

int main()
{
    INTERPRETATION *inter=INTERPRETATION_create();
    INTERPRETATION_print(*inter); // works fine

    // by default an uninitialised bool variable takes false as an initial value
    // so all the values in the array inter->variables  are false

    INTERPRETATION_update(inter,2,true); // a Segmentation fault

    return 0;
}

INTERPRETATION * INTERPRETATION_create(){
    INTERPRETATION inter;
    INTERPRETATION *ptr;
    inter.number_of_var=4;
    inter.variables=(bool*) malloc(inter.number_of_var * sizeof(bool));
    ptr=&inter;

    return ptr;
}

void INTERPRETATION_update(INTERPRETATION *inter,int var,bool value){
    inter->variables[var-1]=value; // a Segmentation fault
}

void INTERPRETATION_print(INTERPRETATION inter){
    int i=0;
    for (i;i<inter.number_of_var;i++ ){
        printf("variable%d=",(i+1));
        printf(inter.variables[i] ? "true\n" : "false\n");
    }
}
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
ar designs
  • 11
  • 2
  • 5
    You're returning a pointer to a local variable. The local variable goes out of scope when the function returns. – Retired Ninja Jun 10 '20 at 16:20
  • 1
    `ptr=&inter; return ptr;` is a big no-no – UnholySheep Jun 10 '20 at 16:20
  • I cannot compile your code. You can post all of your code, or use our tool to debug it by following this [instruction](https://www.cee.studio/segfault.html). – stensal Jun 10 '20 at 16:21
  • *"by default an uninitialised bool variable takes false as an initial value"* - that's absolutely not true. An uninitialized variable has an *indeterminate value* – UnholySheep Jun 10 '20 at 16:22
  • is there a way to return the pointer whithout using a local variable,so it wont get deallocated? – ar designs Jun 10 '20 at 16:29
  • thanks for the info ,i printed the array and all the variables are false so i just assumed that the default value is false . – ar designs Jun 10 '20 at 16:31
  • @ardesigns please note how I didn't reproduce the crash on Windows with the attached code. That happens when _undefined behavior_ is caused. Depending on the contents of the memory the crash may or may not occur. It seems a common mistake: I answered to a [similar question](https://stackoverflow.com/a/62247846/11336762) some days ago . Give it a read. – Roberto Caboni Jun 10 '20 at 16:57

0 Answers0