Causes of Memory Leaks in C Language

Causes of Memory Leaks in C Language1 Uninitialized Pointer in Struct Member

struct student{    char *name;  // Only 4 bytes allocated, not pointing to a valid address, contains garbage values        int score;}stu, *pstu;
int main(){    strcpy(stu.name, "code"); // This will cause an error, the solution is to malloc space for the name pointer        stu.score = 99;    return 0;}

Another error:

int main(){    pstu = (struct student *)malloc(sizeof(struct student)); // Memory for name not allocated, just assumed it was.    strcpy(pstu->name, "code");    pstu->score = 99;    free(pstu);    return 0;}

2 Insufficient Memory Allocation for Struct Pointer

int main(){    pstu = (struct student *)malloc(sizeof(struct student *)); // Incorrectly wrote sizeof(struct student *), leading to insufficient memory    strcpy(pstu->name, "code");    pstu->score = 99;    free(pstu);    return 0;}

3 Memory Out of Bounds Memory allocated successfully and initialized, but operations exceeded memory boundaries. This error often occurs due to “off by one” errors when manipulating arrays or pointers. For example:

int a[10] = {0};for (i=0; i<=10; i++) // This goes out of bounds, one too many {    a[i] = i;}

Therefore, the loop variable in a for loop should always use a half-open interval, and if not in special cases, the loop variable should ideally start from 0.4 Memory Leak Generally occurs when memory allocated by malloc or the new operator is not freed or deleted in a timely manner after use, leading to memory not being released until the program ends.

(void *)malloc(int size)  // Function prototype
/* Specific usage */char *p = (char *)malloc(100);  // Type casting is required, and a pointer must be specified to receive the starting address of the allocated memory, after which the memory can be accessed through the pointer variable p, as the memory has no name, it is accessed anonymously
/* There is a possibility of allocation failure, so it should be used */ if(NULL != p)/* to verify that memory was indeed allocated successfully */
/* After freeing memory, p's value should be set to NULL, otherwise a dangling pointer may occur */p = NULL;

Source: https://www.zhihu.com/answer/2507123829

Leave a Comment