tags:

views:

156

answers:

3

I get the following error in my C program:

Writing to heap after end of help buffer

Can you tell me what I'm missing?

char * path_delimiter(char * path)
{
    int i = 0, index = 0, size = 0, length = (int)strlen(path);
    char *tmp, *ans;

    for(; i < length; i++) {
        if(path[i] == PATH_DELIM[0]) {
          break;
        }
    }
    i++;
    size = (int)strlen(path) - i;
    ans = (char*)malloc(sizeof(path));
    tmp = (char*)malloc(size);
    strcpy(ans,path);
    ans[i-1] = END_ARRAY;

    if(size > 0)
    {
        strcpy(tmp,&path[i]);
        realloc(path,size);
        strcpy(path,tmp);
    }
    else 
    {
        strcpy(path,ans);
    }
free(tmp);

return ans;
}
+5  A: 

You are not checking if malloc and realloc succeeded. More importantly, realloc may return a different handle which you are discarding.

Further, you have:

ans = malloc(sizeof(path));
...
strcpy(ans, path);

On the most common platform today, sizeof(path) is most likely 4 or maybe 8, regardless of the length of the character array path points to.

Sinan Ünür
+8  A: 

This ...

sizeof(path)

... is the same as ...

sizeof(char *)

... which is the size of the pointer (not the size of the buffer which it's pointing to), so it's probably about 4.

So this ...

ans= (char*)malloc(sizeof(path));

... is a 4-byte buffer, and so this ...

strcpy(ans,path);

... is overwriting (writing past the end of) that buffer.

Instead of ...

malloc(sizeof(path));

... I think you want ...

malloc(strlen(path)+1);
ChrisW
To the OP: Please, use strncpy for now on. It will save you a lot of headaches down the road.
Calyth
Shouldn't that be: malloc(sizeof(char)*(strlen(path)+1));You are assuming the char is 1 byte.
Andrew
Andrew, I think `sizeof(char)` always equals 1, by definition.
ChrisW
@Calyth - strncpy() is not a panacea; it does not always null terminate the string it copies, and it always writes as many characters as you tell it there is space for (which are not contradictory statements, though it might seem like that).
Jonathan Leffler
A: 

You normally need size = strlen(xxx) + 1; to allow for the null terminator on the string.

In this case, I think you need:

size = strlen(path) - i + 1;
Jonathan Leffler
thans for you all its solve my problem... but to be sure when i use the method strlen i need to add 1 for the '\0' if not then why do i need the +1 thanks again
eran
The `strlen()` function counts the number of characters in the string excluding the terminating null. When you allocate memory, you must allocate enough memory for the string including the terminating null, which is therefore 'strlen(whatever)+1' bytes.
Jonathan Leffler