sagi
sagi

Reputation: 522

freeing 2 pointers which have the same address

I have the following 2 code samples:

char *p1, *p2;
...
p1 = strdup("my str");
p2 = p1; 
...
free(p2);
p2 = NULL;
...
free(p1);

And the following code:

p1 = strdup("my str");
...
free(p1);
...
free(p1);

The second block, obviously, fails with double free. The question is, why the first code block exit successfully?

Upvotes: 0

Views: 184

Answers (3)

sagi
sagi

Reputation: 522

So i found that in this case valgrind does not help but dmalloc comes to the rescue.

debug-malloc library: dumping program, fatal error
   Error: tried to free previously freed pointer (err 61)
Aborted (core dumped)

Upvotes: 0

Vittorio Romeo
Vittorio Romeo

Reputation: 93284

You have a double free in both code snippets. Double free is undefined behavior: anything can happen, including crashing or exiting successfully.

As an example, your first snippet crashes here on coliru.

Upvotes: 0

P.P
P.P

Reputation: 121397

The question is, why the first code block exit successfully ?

Both result in undefined behaviour and have got the same problem. One fails while other isn't may just be coincidence. That's how UB works.

But in all probability, I'd have expected the first to fail with double-free as well.

A similar example:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>


int main (void)
{
    char *p1, *p2;
    p1 = strdup("my str");
    p2 = p1;
    free(p2);
    p2 = NULL;
    free(p1);
}

I tried on both http://ideone.com/TwWDRr and on my Linux machine fail with double-free.

Upvotes: 3

Related Questions