Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

316
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda