Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

c - Memory Clobbering Error

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
", i, ptr[i]);
        ptr++;
    }
    free(ptr);


    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 with p leaving ptr intact so you can free(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 like ptr[i], if you mess with the ptr pointer, you are changing the base address and accessing the characters with ptr[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:

int main(int argc, char *argv[]){

    char *ptr = NULL;
    char * p; 

    ptr = (char *) malloc(LEN+1);// +1 for string (please check for NULL)
    p = ptr;

    strcpy(ptr, "hello");

    int i = 0;
    while (*p) // note how I changed it to a while loop, C strings are NULL terminated, so this will break once we get to the end of the string. What we gain is that this will work for ANY string size.
    {
        printf("ptr[%d] = %c
", i++, *p); // here i dereference the pointer, accessing its individual char
        p++;
    }
    free(ptr);


    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...