C Compiler Logo

Memory Leak

Memory Leak

runtime

No runtime error, but program consumes increasing amounts of memory

Description

The program allocates memory but never frees it, causing the program to consume more and more memory over time.

Common Causes

Example of Error

Error Code

void processData() {
    int *data = malloc(1000 * sizeof(int));
    // Process data
    // Missing free(data)
}

int main() {
    while (1) {
        processData();  // Memory leak on each call
    }
    return 0;
}

Solution

Always free dynamically allocated memory when it's no longer needed.

Corrected Code

void processData() {
    int *data = malloc(1000 * sizeof(int));
    if (data == NULL) {
        return;  // Handle allocation failure
    }
    
    // Process data
    
    free(data);  // Free memory when done
}

int main() {
    while (1) {
        processData();
    }
    return 0;
}

Additional Tips