your programing

C ++에서 포인터 삭제

lovepro 2020. 10. 11. 11:06
반응형

C ++에서 포인터 삭제


문맥 : 나는 포인터를 머리로 감 으려고 노력하고 있는데, 우리는 몇 주 전에 학교에서 그들을 보았고 오늘 연습하는 동안 나는 바보가 되었습니까? 문제, 그것은 당신에게 매우 간단 할 수 있지만 프로그래밍 경험이 거의 없습니다.

나는 포인터 삭제에 관한 몇 가지 질문을 보았지만 모두 '간단한'포인터가 아닌 클래스 삭제와 관련이있는 것 같습니다 (또는 적절한 용어가 무엇이든간에), 여기에 내가 시도하는 코드가 있습니다. 운영:

#include <iostream>;

using namespace std;

int main() {
  int myVar,
      *myPointer;

  myVar = 8;
  myPointer = &myVar;

  cout << "delete-ing pointers " << endl;
  cout << "Memory address: " << myPointer << endl;

  // Seems I can't *just* delete it, as it triggers an error 
  delete myPointer;
  cout << "myPointer: " << myPointer << endl;
  // Error: a.out(14399) malloc: *** error for object 0x7fff61e537f4:
  // pointer being freed was not allocated
  // *** set a breakpoint in malloc_error_break to debug
  // Abort trap: 6

  // Using the new keyword befor deleting it works, but
  // does it really frees up the space? 
  myPointer = new int;
  delete myPointer;
  cout << "myPointer: " << myPointer << endl;
  // myPointer continues to store a memory address.

  // Using NULL before deleting it, seems to work. 
  myPointer = NULL;
  delete myPointer;
  cout << "myPointer: " << myPointer << endl;
  // myPointer returns 0.

}

그래서 내 질문은 다음과 같습니다.

  1. 첫 번째 사례가 작동하지 않는 이유는 무엇입니까? 포인터를 사용하고 삭제하는 가장 간단한 사용법은 무엇입니까? 오류는 메모리가 할당되지 않았지만 'cout'이 주소를 반환했다고 말합니다.
  2. 두 번째 예에서는 오류가 발생하지 않지만 myPointer 값을 cout하면 여전히 메모리 주소가 반환됩니까?
  3. # 3이 실제로 작동합니까? 나에게 일하는 것 같고 포인터가 더 이상 주소를 저장하지 않습니다. 이것이 포인터를 삭제하는 적절한 방법입니까?

긴 질문에 대해 죄송합니다. 가능한 한 명확하게 만들고 싶었습니다. 다시 말하지만 프로그래밍 경험이 거의 없기 때문에 누군가가 평신도의 용어를 사용하여 대답 할 수 있다면 대단히 감사하겠습니다!


1 및 2

myVar = 8; //not dynamically allocated. Can't call delete on it.
myPointer = new int; //dynamically allocated, can call delete on it.

첫 번째 변수는 스택에 할당되었습니다. new연산자를 사용하여 동적으로 (힙에서) 할당 한 메모리에서만 delete를 호출 할 수 있습니다 .

삼.

  myPointer = NULL;
  delete myPointer;

위는 전혀 아무것도 하지 않았습니다 . 포인터가 NULL을 가리 키기 때문에 아무것도 해제하지 않았습니다.


다음은 수행하면 안됩니다.

myPointer = new int;
myPointer = NULL; //leaked memory, no pointer to above int
delete myPointer; //no point at all

NULL을 가리키고 누수 된 메모리 (사용자가 할당 한 새 정수)를 남겨 둡니다. 가리키는 메모리를 해제해야합니다. new int더 이상 할당 된 항목에 액세스 할 방법이 없으므로 메모리 누수가 발생합니다.


올바른 방법 :

myPointer = new int;
delete myPointer; //freed memory
myPointer = NULL; //pointed dangling ptr to NULL

더 나은 방법 :

C ++를 사용하는 경우 원시 포인터를 사용 하지 마십시오 . 대신 약간의 오버 헤드로 이러한 일을 처리 할 수있는 스마트 포인터사용하십시오 . C ++ 11에는 여러 .


I believe you're not fully understanding how pointers work.
When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new operator).

Imagine:

int *ptr = new int; 
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
//   notice from your 2nd test) but what inside that memory is gone!

When you did

ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.

C++ allows that you try to delete a pointer that points to null but it doesn't actually do anything, just doesn't give any error.


Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.

You can however use pointers to allocate a 'block' of memory, for example like this:

int *some_integers = new int[20000]

This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.

Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:

delete [] some_integers;

Hope that helps.


There is a rule in C++, for every new there is a delete.

  1. Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.

new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:

myPointer = &myVar;

you say:

myPointer = The address of where the data in myVar is stored

  1. On the second example the error is not being triggered but doing a cout of the value of myPointer still returns a memory address?

It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.

  1. Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?

NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:

myPointer = NULL;

which equals:

myPointer = 0;

  1. You are trying to delete a variable allocated on the stack. You can not do this
  2. Deleting a pointer does not destruct a pointer actually, just the memory occupied is given back to the OS. You can access it untill the memory is used for another variable, or otherwise manipulated. So it is good practice to set a pointer to NULL (0) after deleting.
  3. Deleting a NULL pointer does not delete anything.

int value, *ptr;

value = 8;
ptr = &value;
// ptr points to value, which lives on a stack frame.
// you are not responsible for managing its lifetime.

ptr = new int;
delete ptr;
// yes this is the normal way to manage the lifetime of
// dynamically allocated memory, you new'ed it, you delete it.

ptr = nullptr;
delete ptr;
// this is illogical, essentially you are saying delete nothing.

참고URL : https://stackoverflow.com/questions/13223399/deleting-a-pointer-in-c

반응형