I have a small piece of code. I compiled it with -lmcheck
as I am trying to debug a code where I have the same similar error.
I get this error when I run this code:
memory clobbered before allocated block
Can someone explain the reason why free(ptr)
will throw me this error?
How else can I free the pointer?
Thanks.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define LEN 5
int main(int argc, char *argv[]){
char *ptr = NULL;
ptr = (char *) malloc(LEN+1);// +1 for string
strcpy(ptr, "hello");
int i = 0;
for(i = 0; i<LEN; i++)
{
printf("ptr[%d] = %c\n", i, ptr[i]);
ptr++;
}
free(ptr);
return 0;
}
Find the answer in comments. When you allocate some memory, typically, the memory management framework keep tracks of it by adding some more info (you can say Header and Footer) to the allocated memory area. When you free this memory, the same info is matched so as to detect any unwanted/invalid memory access.
Because
ptr
no longer points to the base of the memory you allocated.Also, after you increment
ptr
, the expressionptr[i]
does not return what you might expect; and that is why the output starts with "hlo".You are incrementing
ptr
, therefore changing the address that it points to. You can't do that.In your case, have a separate pointer, let's say
char * p = ptr
and do your operations withp
leavingptr
intact so you canfree(ptr)
later.EDIT Taking a second look at your code, I found that you are doing
ptr++
when you shouldn't. You are accessing the characters in the array likeptr[i]
, if you mess with theptr
pointer, you are changing the base address and accessing the characters withptr[i]
can lead (and will lead) to unexpected results.If you simply remove that line (
ptr++
) your code will magically work. If you want to explore the pointer concept and try another solution, your code could look something like this: