I am wondering what happens to a struct element that points to a non-dynamically distributed 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 that it is destroyed, no longer indicates the year right? If so, would the same be true if * a pointer pointing to the correct function?
like this:
typedef struct { int value; void (*someFunc)(); } MyStruct;
Then later:
void sayHi(){ printf("hi"); } ... myStruct->someFunc = sayHi;
No special cleanup is required other than free () if our structure was created using malloc? Thanks for any information anyone has.
source share