Talking about the difference between wild pointer and null pointer

Null pointer

  1. A pointer that does not store any memory address is called a null pointer (NULL pointer).

  2. A null pointer is a pointer assigned a value of 0, and its value is 0 before being initialized.

     int *s1 = NULL;
    

Wild pointer

  1. A wild pointer is not a NULL pointer, but a pointer to "garbage" memory (unavailable memory).
  2. In a computer, the allocation of memory is managed by the operating system. To use memory, you need to apply to the operating system.
  3. The memory space of the wild pointer is randomly allocated by the system, which is an illegal access to the memory.

Harm
  When a pointer is called a wild pointer, its pointing is random. When you use a pointer with a random address, the degree of harm is also random. Generally, it will cause memory leaks. Hackers put the virus into this memory. When you use this pointer, the virus will start to execute.

produce

  1. Not initialized when creating the pointer
  2. After freeing the pointer, it did not point to NULL
  3. Use pointers outside the scope of pointer variables

avoid

  1. When defining a pointer, initialize it. If there is no definite value, let it point to NULL. Because NULL is #define NULL(void **) 0 in the macro definition, it represents a zero address, which cannot be read or written.

  2. When you need to assign a value to the space pointed to by the pointer, check whether the pointer has allocated space, and check the validity before using the pointer.

     int *p = malloc(sizeof(int));
     //这里说明一下为什么赋值的是int整形类型的字节长度,而不是4,因为不同平台上的整形类型的字节长度不相同,
     //如果要跨平台使用会带来不必要的麻烦,这要就很好的提高了代码的移植性
     if (p == NULL)
     {
     	printf("分配失败\n");
     	exit(1);//跳出整个程序,return是跳出一个程序
     }
    
  3. To initialize the allocated space, you can use memset(p, 0, sizeof(int)) to set the space pointed to by the pointer to 0.

  4. After the pointer is used, it must be released in time, and the corresponding malloc is free().

  5. After release, change the pointer to NULL, otherwise a wild pointer will be generated.

Memory leak

  Due to negligence or error, the program did not release the unused memory in time. Memory leak is not the disappearance of memory in the physical sense, but because the program allocates a section of memory, it cannot control this section of memory, which causes a waste of memory. .
  Mainly divided into
    1. Illegal access to space
    2. Access to the released space

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/112732050