tags:

views:

98

answers:

4
int main(void) {
  int* p = (int*) malloc(sizeof(int));
  int* q = (int*) malloc(sizeof(int));
  *p = 10;
  *q = 20;
  p = q;
  printf(“%d %d”, *p, *q);
  free(p); 
  free(q);
}

Why does the above code contain use-after-free error? There's no more expression after free(p) and free(q). Obviously we are not using them anymore!

+12  A: 

You have two problems here.

First, you are deleting the same heap variable twice:

  free(p); 
  free(q);

Second, you have a memory-leak, because the variable created by p is no longer accessible.


Notice that onebyone's comment is really important. If you change the line:

p = q;

into:

*p = *q;

There would be no problems at all in your code :) Hello Pointers!

AraK
Yeap.................
Macroideal
+3  A: 

You set p to q, so you are free()ing it twice.

Zifre
+2  A: 

Since q and p point to the same memory at the point you are freeing them, you're effectively freeing the memory twice.

Hank Gay
+2  A: 

Because here:

p = q;

...you're throwing away the old value of p. You now have two copies of the pointer that was returned by the second malloc, and none of the pointer that was returned by the first malloc.

So then here:

free(p); 
free(q);

...the same pointer value gets passed to free twice: use-after-free error. The other pointer value never gets passed to free at all: memory leak.

caf