1

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?

richardaum
  • 6,651
  • 12
  • 48
  • 64
  • Did you consider printing the pointer after calling `free`? – Corbin May 22 '12 at 05:57
  • 1
    Never typecast the result of malloc. Read [this](http://c-faq.com/malloc/mallocnocast.html) and [this](http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc). – Lundin May 22 '12 at 06:49

3 Answers3

5
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);
cnicutar
  • 178,505
  • 25
  • 365
  • 392
3

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;
Jay
  • 24,173
  • 25
  • 93
  • 141
  • 1
    Or simply write two lines of code instead of one, it won't kill you. It will make it more obvious what the code is doing. Don't attempt to re-define the C language. – Lundin May 22 '12 at 06:48
  • 1
    @Lundin I don't really see a problem with it if he is going to be doing it a lot of places. I feel like using a language construct isn't redefining the language. Although a better name might be a good idea. – grinch Nov 18 '12 at 03:22
2

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.

ugoren
  • 16,023
  • 3
  • 35
  • 65