1

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; } 
2
  • Please edit to format your code: Click the 1010 link and indent each code line 4 spaces - more to show indenting within the code. Commented Oct 9, 2009 at 13:26
  • 3
    It would help to know what you are trying to do. For example, what do you think malloc(sizeof(path)) does? Commented Oct 9, 2009 at 13:32

3 Answers 3

8

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); 
Sign up to request clarification or add additional context in comments.

4 Comments

To the OP: Please, use strncpy for now on. It will save you a lot of headaches down the road.
Shouldn't that be: malloc(sizeof(char)*(strlen(path)+1)); You are assuming the char is 1 byte.
Andrew, I think sizeof(char) always equals 1, by definition.
@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).
5

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.

Comments

0

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; 

2 Comments

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
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.