Z
Z
ZaHaR_352022-01-23 00:33:50
C++ / C#
ZaHaR_35, 2022-01-23 00:33:50

What is the difference between delete and nullptr?

Why if you create a pointer to char in c++, then copy this pointer, then if you delete it, the value of the copied pointer will be undefined, and if you make the initial pointer nullptr, then the copied pointer will have its original value?
Here is an example:

char* g = new char[10];
  strcpy_s(g, 6, "hi");
  char* gg = g;
  g = nullptr; // Здесь всё нормально, но если сделать delete[] g, то будет неопределенное поведение
  std::cout << gg;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2022-01-23
@ZaHaR_35

g = nullptr does not delete memory, it simply writes a value to the variable g with the meaning - "pointer to nowhere". The memory remains intact and can be accessed, which you do by storing the pointer in another variable.
delete[] releases the memory, which means that all subsequent calls to it, either with g or with gg, will cause UB

A
Adamos, 2022-01-23
@Adamos

In C++, you need to understand the truth: there is no garbage collector!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question