Pointer being realloc’d was not allocated

Error: pointer being realloc’d was not allocated

In C programming, this error occurs when you try to reallocate memory using the realloc() function for a pointer that was not previously allocated using malloc(), calloc(), or realloc().

The realloc() function is used to resize the memory block pointed to by a pointer. However, it can only be used on pointers that were allocated dynamically using malloc(), calloc(), or realloc().

Here’s an example that demonstrates this error:

// Incorrect usage of realloc()
int* pointer = NULL;
pointer = realloc(pointer, 10 * sizeof(int)); // Error: pointer not allocated

In the above example, the pointer variable is initially set to NULL, which means it doesn’t point to any allocated memory. Then, we try to reallocate memory for 10 integers using realloc(). Since the pointer was not previously allocated, it results in the “pointer being realloc’d was not allocated” error.

To fix this error, you need to ensure that the pointer is allocated using malloc(), calloc(), or realloc() before trying to reallocate it. Here’s the corrected version of the above example:

// Correct usage of realloc()
int* pointer = NULL;
pointer = malloc(10 * sizeof(int)); // Allocate memory
pointer = realloc(pointer, 20 * sizeof(int)); // Resize memory

In this corrected example, we first allocate memory for 10 integers using malloc(). Then, we resize the memory block to accommodate 20 integers using realloc(). Since the pointer was properly allocated, it does not result in the “pointer being realloc’d was not allocated” error.

Leave a comment