C Compiler Logo

Memory Corruption

Memory Corruption

memory

heap corruption detected

Description

The program writes to memory in a way that corrupts the heap or stack, often leading to crashes or unpredictable behavior.

Common Causes

Example of Error

Error Code

int main() {
    int *arr = malloc(5 * sizeof(int));
    arr[10] = 42;  // Writing beyond allocated memory
    free(arr);
    return 0;
}

Solution

Ensure all memory accesses are within allocated bounds and initialize pointers before use.

Corrected Code

int main() {
    int *arr = malloc(5 * sizeof(int));
    if (arr != NULL) {
        for (int i = 0; i < 5; i++) {
            arr[i] = i;  // Stay within bounds
        }
        free(arr);
    }
    return 0;
}

Additional Tips