richardaum
richardaum

Reputation: 6777

Freeing the memory arrays of structures in C

Assume the following situation:

typedef struct {
    int ID1;
    int ID2;
    char string[256];
} Reg;

I create an array dynamically, this structure:

Reg *myReg = (Reg*) malloc(sizeof(Reg)*100); //array of type Reg with 100 positions.

And throughout this example system, I fill this array.

There comes a certain point I do not want the pointer "myReg" point to this vector. I want him to point to NULL. And also to clear the memory space occupied by malloc I did.

question:

If I do:

free(myReg);

This will make myReg will point to NULL and release the space taken up that I've allocated?

Upvotes: 1

Views: 5244

Answers (3)

ugoren
ugoren

Reputation: 16451

Other answers are correct.

To help understanding why it must be so, consider that there may be multiple pointers pointing to this memory, or to different parts of it:

Reg *myReg = (Reg*) malloc(sizeof(Reg)*100);
Reg *myReg2 = myReg;
Reg *myReg3 = &myReg[50];

When you free myReg, all these pointers are unchanged. They point to the same piece of memory as before, but this memory must no longer be used.
You, the programmer, should set them to NULL (or just avoid using them after free).
C can't find them all and set them to NULL. More modern languages, such as Java, know how to track all the pointers to a given object, but C does nothing like this.

Upvotes: 2

Jay
Jay

Reputation: 24905

A call to free only free's the memory allocated and returns it to the heap. It will not set the your myReg to NULL. You must do it yourself.

One way is to write a macro as below:

#define MY_FREE(ptr) free(ptr); ptr = NULL;

Upvotes: 3

cnicutar
cnicutar

Reputation: 182744

free(myReg);

This will make myReg will point to NULL and release the space taken up that I've allocated?

It will only release the memory. Even without reading the specs, if you look at how the free function is declared, you'll see it can't actually change what the pointer is pointing to.

/* Even if it wanted, `free` can't make `ptr` point to anything else. */
void free(void *ptr);

Upvotes: 5

Related Questions