After I call free
on a struct variable in C, and then check if that variable is NULL, it shows me that it is NOT NULL. So free
did not work? My code:
struct main_struct {
struct my_file *file;
};
struct my_file {
char *host;
int port; // this cannot be malloc'ed and free'ed
};
struct my_file* read_file() {
FILE *f;
struct my_file *file;
//open FILE for reading..
file = malloc(sizeof(struct my_file)); //allocate memory for my_file struct
memset(file, 0, sizeof(struct my_file));
// while loop to read file content..
// in the loop:
char *value = line;
file->host = malloc(sizeof(char) * strlen(value)); //allocate memory for host member variable
strncpy(file->host, value, strlen(value)); //assign value to host variable
return file;
}
int main() {
struct main_struct *mstr;
mstr = malloc(sizeof(struct main_struct)); //allocate memory to main_struct
memset(mstr, 0, sizeof(struct main_struct));
mstr->my_file = read_file(); //call to read file, allocate mem for my_file struct and the 'host' member variable
// some code
// call free here:
if(mstr->my_file->host != NULL) {
free(mstr->my_file->host);
}
// check if mem has been freed:
if(mstr->my_file->host == NULL) {
printf("mstr->my_file->host is NULL, good.\n");
} else {
printf("mstr->my_file->host is NOT NULL, bad.\n"); // I see this.
}
// I also try to free mstr->my_file:
if(mstr->my_file != NULL) {
free(mstr->my_file);
}
// check if mem has been freed:
if(mstr->my_file == NULL) {
printf("mstr->my_file is NULL, good.\n");
} else {
printf("mstr->my_file is NOT NULL, bad.\n"); // I see this.
}
// and also mstr itself..
}
Am I using the free
function correctly, because I have seen examples where free
has been called like this:
free(&mystruct->myfile->host);
by sending the address of the pointer to free. But I think that the way I am calling free now, is correct..?