Doubt in dynamic memory allocation

Asked

Viewed 111 times

3

In the code below, release B memory also releases from A?

int* A = new int[4]; 
int *B = A; 
delete[] B;

1 answer

2


Yes, because both pointers point to the same memory region..

Keep in mind that the pointer only indicates where your data is, deleting B does not erase A, deletes the content also pointed by A.

After allocation: inserir a descrição da imagem aqui After the release of memory: inserir a descrição da imagem aqui

Also note that A remains pointed at the memory region, while B after delete points to an explicitly invalid region.

  • 4

    "Observe também que A continua apontado para a região de memória, enquanto B após o delete aponta para uma região explicitamente inválida." ??? A and B remain the same as pointing to the same memory region, a potentially invalid.

  • 1

    Thanks for the personal clarification.

  • @Guilhermebernal tested in Visual Studio and I suggest you do this too... the construction Assembly generates the instruction mov dword ptr[B], 8123h which modifies pointer B after memory wipe call operator delete (0124108Ch)

  • 3

    @Leonardobosquett Errado. What happens is that if, after deleting the memory, you try to read again by the same pointer, you can get a valid reading of an unknown value by which the memory was reused. What Visual Studio Does, only in the debug mode, is to set the pointer to a value that will undoubtedly cause crash (0x00008123). So you’re warned if you do something wrong, instead of having a program that apparently works. However, he does not notice the relationship between B and A and only arrow B. This is an extra of VS, not a correct C++ behavior. Do not limit yourself to VS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.