C Language-----Wild pointer

Source: Internet
Author: User

The problem lies

1. The local pointer variable is not initialized

2 . Use a pointer that has been released

3 . The variable pointed by the pointer is destroyed before the pointer

4, struct member pointer is not initialized, not enough memory allocated for struct pointer, memory out of bounds (consider using flexible array) and leaking

Avoid rules

1 . After requesting memory with malloc, you should immediately check that the pointer value is NULLand prevent the use of a null -valued pointer

< Span class= "FONTSTYLE0" > 2, remember the length of the array, prevent the array from crossing the operation, Consider using a flexible array

3. Dynamic request operation must match the release operation to prevent memory leaks and multiple releases
4. The free pointer must immediately be assigned a value of NULL


malloc is used to allocate a specified size of memory from the heap, returning the starting address of the memory in the type void *. The parameter of malloc is the size of the memory to allocate, in bytes.
Therefore, if you want to allocate 1 integer spaces, you need malloc (sizeof (int)), because the returned void * cannot be directly assigned to int *, you also have to cast the type conversion int * s= (int*) malloc (sizeof (int)).

struct Student
{
char* name;
int number;
};

int main ()
{
struct Student s;

strcpy (S.name, "gggg");   oops! The wild pointer, cannot be arbitrarily assigned, because S is a local variable, the address saved by name is a random value and cannot be written to a random value////////////////////////// ///////////////////

S.number = 99;


return 0;
}

C Language-----Wild pointer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.