Programing

매달린 포인터와 메모리 누수의 차이점

lottogame 2020. 10. 16. 07:02
반응형

매달린 포인터와 메모리 누수의 차이점


매달린 포인터와 메모리 누수의 차이를 이해하지 못합니다. 이 두 용어는 어떤 관련이 있습니까?


매달려 포인터가 이미 해제 된 메모리에 포인트. 스토리지가 더 이상 할당되지 않습니다. 액세스를 시도하면 분할 오류가 발생할 수 있습니다.

매달린 포인터로 끝나는 일반적인 방법 :

char *func()
{
   char str[10];
   strcpy(str, "Hello!");
   return str; 
}
//returned pointer points to str which has gone out of scope. 

호출 함수로 컨트롤이 반환 된 시간에 의해 범위를 벗어난 지역 변수 인 주소를 반환합니다. (정의되지 않은 동작)

또 다른 일반적인 매달려 포인터 예제는 해당 메모리에서 free가 명시 적으로 호출 된 후 포인터를 통해 메모리 위치에 액세스하는 것입니다 .

int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!

메모리 누수가 그것을 얻을 수있는 어떤 방법이 더 이상 존재하지으로, 이제 (그것을 해제 또는) 해제되지 않은 메모리를 액세스 할 수있는 방법이 없습니다. (예 : 동적으로 할당 된 (해제되지 않은) 메모리 위치 대한 유일한 참조 였으며 지금은 다른 곳을 가리 킵니다.)

void func(){
    char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory

Char-ptr ch는 함수 끝에서 범위를 벗어나 동적으로 할당 된 10 바이트를 유출하는 지역 변수입니다 .


이것들은 서로의 반대라고 생각할 수 있습니다.

메모리 영역을 해제했지만 여전히 포인터를 유지하면 해당 포인터가 매달려 있습니다.

char *c = malloc(16);
free(c);
c[1] = 'a'; //invalid access through dangling pointer!

포인터를 잃어 버렸지 만 할당 된 메모리를 유지하면 메모리 누수가 발생합니다.

void myfunc()
{
    char *c = malloc(16);
} //after myfunc returns, the the memory pointed to by c is not freed: leak!

매달려 포인터가 예상 개체의 유형에 대해 유효하지 않은 일부 메모리를 참조하는 값 (하지 NULL)가 하나입니다. 예를 들어 객체에 대한 포인터를 설정 한 경우 관련없는 다른 메모리로 해당 메모리를 덮어 쓰거나 동적으로 할당 된 경우 메모리를 해제합니다.

메모리 누수가 동적으로 힙에서 메모리를 할당하지만 결코 당신이 그것에 대한 모든 참조를 손실 가능성이 있기 때문에, 그것을 해제 할 때입니다.

둘 다 잘못 관리 된 포인터, 특히 동적으로 할당 된 메모리와 관련된 상황이라는 점에서 관련됩니다. 한 상황 (매달린 포인터)에서 메모리를 해제했을 가능성이 있지만 나중에 참조하려고했습니다. 다른 하나 (메모리 누수)에서는 메모리를 완전히 해제하는 것을 잊었습니다!


댕글 링 포인터

어떤 포인터가 변수의 메모리 주소를 가리키고 있지만 포인터가 여전히 그러한 메모리 위치를 가리키는 동안 해당 메모리 위치에서 일부 변수가 삭제 된 후. 이러한 포인터를 댕글 링 포인터 라고하며이 문제를 댕글 링 포인터 문제라고합니다.

#include<stdio.h>

  int *call();

  void main(){

      int *ptr;
      ptr=call();

      fflush(stdin);
      printf("%d",*ptr);

   }

 int * call(){

   int x=25;
   ++x;
   return &x;
 }

출력 : 가비지 값

참고 : 일부 컴파일러에서는 로컬 변수 또는 임시 주소를 반환하는 경고 메시지가 표시 될 수 있습니다.

설명 : 변수 x는 지역 변수입니다. 범위와 수명은 함수 호출 내에 있으므로 x 변수 x의 주소를 반환 한 후 죽고 포인터는 여전히 ptr을 가리키고 있습니다.

이 문제의 해결책 : 변수 x를 정적 변수로 만드십시오. 즉, 포인팅 객체가 삭제 된 포인터를 댕글 링 포인터라고 할 수 있습니다.

메모리 누수

In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations. As per simple we have allocated the memory and not Free other language term say not release it call memory leak it is fatal to application and unexpected crash.


Pointer helps to create user defined scope to a variable, which is called Dynamic variable. Dynamic Variable can be single variable or group of variable of same type (array) or group of variable of different types (struct). Default local variable scope starts when control enters into a function and ends when control comes out of that function. Default global vairable scope starts at program execution and ends once program finishes.

But scope of a dynamic variable which holds by a pointer can start and end at any point in a program execution, which has to be decided by a programmer. Dangling and memory leak comes into picture only if a programmer doesnt handle the end of scope.

Memory leak will occur if a programmer, doesnt write the code (free of pointer) for end of scope for dynamic variables. Any way once program exits complete process memory will be freed, at that time this leaked memory also will get freed. But it will cause a very serious problem for a process which is running long time.

Once scope of dynamic variable comes to end(freed), NULL should be assigned to pointer variable. Otherwise if the code wrongly accesses it undefined behaviour will happen. So dangling pointer is nothing but a pointer which is pointing a dynamic variable whose scope is already finished.


Memory leak: When there is a memory area in a heap but no variable in the stack pointing to that memory.

char *myarea=(char *)malloc(10);

char *newarea=(char *)malloc(10);

myarea=newarea;

Dangling pointer: When a pointer variable in a stack but no memory in heap.

char *p =NULL;

A dangling pointer trying to dereference without allocating space will result in a segmentation fault.


A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.

#include <stdlib.h>
#include <stdio.h> 
 void  main()
 {
    int *ptr = (int *)malloc(sizeof(int));
    // After below free call, ptr becomes a 
    // dangling pointer
    free(ptr); 
 }

for more information click HERE


A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer.

  1. De-allocation of memory
  2. Function Call
  3. Variable goes out of scope

—— from https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/

참고URL : https://stackoverflow.com/questions/13132798/difference-between-dangling-pointer-and-memory-leak

반응형