Software/Embedded system

Dangling Pointer_ChatGPT code review

neovaga 2022. 12. 24. 17:37
반응형

 댕글링 포인터는 포인터가 값이 존재하지 않는 메모리주소를 가르키고 있다는 것이다. 댕글링 포인터가 발생이 되면 시스템에서 심각한 문제가 발생이 된다. Segment fault 라는 크래쉬가 발생이 된다고 보면 된다. 

 

A dangling pointer is a pointer that pointers to some non-existing memory location which means a deallocated memory block.

A dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from memory without modifying the value of the pointer. 

 

이렇게 Dangling pointer에 대해서 정리를 하고 있는데 ChatGPT 가 핫하게 뜨고 있어서 물어봤다. 이건 마치 처음에 네이버지식을 만나서 답을 찾은 느낌이랄까...간단하게 내가 원하는 것을 AI가 친절하게 설명을 해준다. 이건 정말 기대 이상이였다. 

 

무료일때 AI와 챗을 해보자...

https://openai.com/blog/chatgpt/

 

ChatGPT: Optimizing Language Models for Dialogue

We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests. ChatGPT is

openai.com

 

can you explian what is a dangling pointer and give example code?

 

A dangling pointer is a pointer that points to a memory location that has already been deallocated, or freed. This can occur when a pointer is assigned to the address of a dynamically allocated block of memory, and the block of memory is subsequently deleted or deallocated while the pointer is still pointing to it.

Here is an example of code that creates a dangling pointer:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *ptr;

    // Allocate memory for an integer
    ptr = (int *) malloc(sizeof(int));

    // Deallocate the memory
    free(ptr);

    // Use the dangling pointer
    *ptr = 5;

    return 0;
}
 

In this example, the pointer ptr is first assigned the address of a dynamically allocated block of memory using malloc. This block of memory is then deallocated using free, which releases it back to the operating system. However, the pointer ptr is still pointing to the now deallocated memory location, which is a dangling pointer. If the code then tries to access the memory location through the dangling pointer, it can cause a segmentation fault or other undefined behavior.

//Dangling code 찾았던 걸 해석해주고 수정해달라고 했더니... 알아서 적절하게 설명을 해준다.  

#include<stdio.h>

int *fun()
{
    int num = 10;
    return &num;
}

int main()
{
    int *ptr = NULL;
    ptr = fun();
    printf("Test: %d\n",*ptr);

    return 0;
}

➜  11_Pointer gcc 1215_dangling.c 
1215_dangling.c:6:13: warning: address of stack memory associated with local variable 'num' returned [-Wreturn-stack-address]
    return &num;
            ^~~
1 warning generated.
➜  11_Pointer ./a.out 
Test: 10

 This code creates a dangling pointer. The pointer ptr is assigned the address of a local variable num in the function fun. However, num is a local variable and its lifetime ends when the function fun returns. As a result, the pointer ptr is pointing to a memory location that has already been deallocated, which is a dangling pointer.

If the code then tries to access the memory location through the dangling pointer, it can cause a segmentation fault or other undefined behavior. To avoid this issue, it is important to ensure that pointers are only pointing to memory locations that are still valid.

One way to fix this issue would be to dynamically allocate memory for num using malloc and return a pointer to the allocated memory, rather than returning the address of a local variable. This would ensure that the memory remains allocated even after the function returns, and the pointer will not be a dangling pointer.

 

해당 코드는 실제로 segment fault나 문제 없이 실행이 된다. complier에서는 warning이 뜨긴하지만 그래서 이유를 물어봤더니

 

The first version of the code that you provided creates a dangling pointer, but it is still able to run because the operating system has not yet reclaimed the memory location that the pointer is pointing to.

When the memory for the integer num is deallocated using free, it is released back to the operating system, which can then reuse the memory for other purposes. However, the operating system does not immediately reclaim the memory, and the memory location remains valid until it is actually reused.

As a result, the first version of the code is able to run and print the value of *ptr without causing a segmentation fault or other undefined behavior. However, this does not mean that the code is correct or safe to use. Using a dangling pointer can still cause undefined behavior and should be avoided.

#include<stdio.h>
#include<stdlib.h>

int *fun()
{
    // Dynamically allocate memory for num
    int *num = malloc(sizeof(int));
    *num = 10;

    return num;
}

int main()
{
    int *ptr = NULL;
    ptr = fun();
    printf("Test: %d\n",*ptr);

    // Free the dynamically allocated memory
    free(ptr);

    return 0;
}

In this revised version of the code, the function fun dynamically allocates memory for the integer num using malloc, and returns a pointer to the allocated memory. This ensures that the memory remains allocated even after the function returns, and the pointer ptr is not a dangling pointer. The main function then uses the pointer ptr to access the value of num, and frees the dynamically allocated memory using free when it is no longer needed.

This revised version of the code avoids the issue of a dangling pointer, and ensures that the memory is properly deallocated when it is no longer needed.

반응형