int main() { int *ptr = new int(5); delete ptr; // ptr становится висячим указателем. std::cout << sizeof(ptr); // у меня выводит 4 байта. // ... какие-то действия в коде // } 

I declare a pointer that takes 4 bytes in my memory, delete it somewhere at the beginning of the body (as far as I know, delete only frees the memory in which the pointer was located), what happens to the pointer itself? Why does he still occupy some memory? After all, this can affect the speed of my program if I create hundreds of pointers, delete them, and they will still take up some space.

  • Nothing happens to the pointer. only the memory at the address is released, which has a pointer in its meaning - AR Hovsepyan
  • The ptr is a local variable in the main function. Local variable cannot be "deleted". She will retire on completion of the block. delete has nothing to do with it. Why did you add this delete ? - AnT
  • Limit the scope of the variable to curly braces, and you will save the stack. void f(){{int*x=..}{int*y=..}{int*z=..}} . The addresses of the variables x, y, z will be the same. - AlexGlebe 8:32 pm

1 answer 1

You are not right.

 delete ptr; 

frees the memory pointed to by ptr , but not the space occupied by the variable ptr .

sizeof(ptr) says only how much space a variable takes in memory, and does not depend on its value.

The speed of the program, even a hundred pointers somehow unlikely to affect, but the selection / release through new/delete - can. It is the process of isolation and release that is quite long from the point of view of processor time.

  • Is it possible to remove the ptr itself? - Kaznachei
  • one
    If it is a local variable - not until it goes out of scope. If static / global (static storage) - then it exists all the time the program. - Harry
  • If static, will it "live" until the program is completed? And not to delete? - Kaznachei
  • I read, I just wrote, and how I sent it, I jumped out completely from your comment - Kaznachei
  • Not. And why, exactly? :) This is literally bytes ... If large chunks of memory are arrays, for example, then select them using new . - Harry