I’m wondering what happens to a struct member that is pointing to a non-dynamically allocated variable. So:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int value;
int *pointer;
} MyStruct;
int year = 1989;
int main (int argc, const char * argv[]) {
MyStruct *myStruct = (MyStruct *) malloc(sizeof(MyStruct));
myStruct->value = 100;
myStruct->pointer = &year;
year++;
printf("%d \n", *myStruct->pointer);
// what happens to the myStruct->pointer member when we free myStruct ?
free(myStruct);
return EXIT_SUCCESS;
}
I assume it’s destroyed an no longer points to year correct? If that is the case, the same would be true if *pointer where pointing to a function right?
like this:
typedef struct {
int value;
void (*someFunc)();
} MyStruct;
Then later:
void sayHi(){
printf("hi");
}
...
myStruct->someFunc = sayHi;
No special cleanup needed except free() if our struct was created with malloc? Thanks for any insights anyone has.
If you didn’t
malloc(orcalloc/strdup/realloc) it you don’t need to free it. Nothing special is needed – the member variable just points at something, it doesn’t logically “own” the pointed at memory.Your
yearmember variable will still exist and is perfectly valid after youfree(myStruct)–myStruct->pointerwill be invalid to use though