Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

309
Views
Using pointer after free() in C99?

My professor showed the following code:

void *p1=malloc(1024);
free(p1);
void *p2=malloc(1024);
if (p1==p2)
{
    printf("Now What?")
}

and he said it's unsafe, but why?

I know we shouldn't try access memory which was freed. However, it's OK to know where the pointer is pointing since it's just a normal pointer, as long as we don't try to read from where it's pointing to.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

This is in fact unsafe because a pointer to freed memory is indeterminate.

Annex J.2 of the C standard, which gives examples of undefined behavior, includes the following:

  • The value of a pointer to an object whose lifetime has ended is used (6.2.4).

...

  • The value of a pointer that refers to space deallocated by a call to the free or realloc function is used (7.22.3).

Where section 7.22.3p1 regarding memory management functions states:

... The lifetime of an allocated object extends from the allocation until the deallocation ...

And section 6.2.4p2 which defines the lifetime of an object states:

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!