Typical error of pointer

  1. Dangling references Vs. Memory leak
    1. Dangling references
      1. Uninitialized pointer
      2. A typical example
    2. Memory leak
  2. Conclusion
  3. References

Dangling references Vs. Memory leak

Dangling references

A dangling reference(i.e., wild pointer or dangling pinter) is a reference to an object that no longer exists or cannot access.

For example:

int* p = new int;
delete p;

int i = *p; // error, p has been deleted!

Practically, if there are multiple pointer to the same memory, once one of the pointer has released the memory and other pointers still reference it, this is dangling references.

Uninitialized pointer

In some cases, the uninitialized pointer is intended as the wild pointer:

char* str;  // wild pointer
static char* str; // not wild pointer because it is initialized to 0 in the .bss memory segment

Note: In this case the pointer str to a random memory(i.e. garbage value) instead of NULL. Therefore, wild pointer and NULL pointer are different.

  • NULL pointer to address 0.
  • wild pointer to a random address(garbage).

A typical example

int main()
{
    int* i = func();
}

int* func(void)
{
    int num = 1234;
    /* ... */
    return # //return an address of a local variable
}

Here, we try to return the address of the local variable &num. However, num is a local variable which stored at stack segment, once the function have been executed, this memory will be released. In this stage, i is the dangling reference.
If we want to return the pointer to num, a feasible method is to guarantee the lifecycle of num is the whole runtime. E.g., we can set the num as static int num.

Memory leak

Memory leak refers to the heap memory segment. It means that the allocated memory by malloc dynamically cannot be released by free correctly. Then this memory block can not be reused until the end of the program.

Conclusion

In a word, below is a safer method to avoid the dangling pointer and wild pointer:

int* p = NULL; //initialize to address 0 or pointer to valid memory
p = (int*)malloc(sizeof(int));
...
free(p);
p = NULL; // reference to NULL to avoid the later dereference operation of p

Note: here the free function only means free the memory instead of delete p. Pointer p is a data type, which will be destroyed until out of the scope.

References


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 gzrjzcx@qq.com

文章标题:Typical error of pointer

文章字数:373

本文作者:Alex Zou

发布时间:2019-02-23, 00:15:35

最后更新:2024-07-10, 03:02:36

原始链接:https://www.hellscript.cc/2019/02/23/subposts_c/Typical-error-of-pointer/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

有钱的捧个钱场,没钱的借钱也捧个钱场