Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use after free error?

Tags:

c

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!

like image 365
user133466 Avatar asked Jul 04 '26 11:07

user133466


2 Answers

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!

like image 141
Khaled Alshaya Avatar answered Jul 06 '26 23:07

Khaled Alshaya


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

like image 43
Zifre Avatar answered Jul 07 '26 01:07

Zifre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!