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;
}
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 = ptrand do your operations withpleavingptrintact 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 theptrpointer, 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: