Realloc (): Invalid next size when redistributing to free up space for strcat on char *

I get an invalid memory error in the following code:

printf(" %s\n","FINE 5"); printf("%s LENGTH IS: %d\n","FINE 6",strlen(": ")); buffer = (char *)realloc(buffer, strlen(buffer)* sizeof(char) + (strlen(": ")+1)* sizeof(char)); printf(" %s\n","FINE 7"); strcat(buffer, ": \0"); 

Output:

FINE 5
FINE 6 LENGTH: 2
* glibc detected * ./auto: realloc (): invalid following size: 0x08cd72e0 *** ======= Backtrace: ========= / lib / tls / i686 / cmov / libc.so .6 (+ 0x6b591) [0x6dd591]

Fine 7 should be noted here. and an incorrect error of the following size at each start is in the same place.

Found this relavent

+8
c string malloc realloc strcat
source share
3 answers

This error occurs because some other part of your code damages the heap. We cannot tell you what kind of error this is without seeing the rest of the code.

The fact that FINE 7 not printed indicates that realloc not working. And this failure should be due to the fact that buffer is invalid due to a heap earlier in the run.


Orthogonal to your actual problem, sizeof(char) is 1 by definition, so it makes sense to remove it from the code.

+6
source share

As David Heffernan points out, your root problem should be a wild pointer elsewhere in your heap-breaking code.

There are several other things to consider in this piece of code:

  • There is no need for sizeof (char) in a new size expression, since sizeof (char) is by definition 1.

  • Never assign a return from realloc directly back to a single pointer to a redistributable buffer. If realloc returns NULL on error, you will lose the pointer to the old buffer and get your own memory leak. You always want to make the corresponding equivalent:

     footype *p = realloc(oldbuff, newsize); if (!p) { handle_error(); } else { oldbuff = p; } 
  • In C, void * will be automatically converted to the correct type when assigned, no need to cast. In addition, when casting in some cases, you will not receive useful error messages when you forget to include the declaration of this function.

  • String literals include the implied terminator nul. You wanted to say:

    strcat (buffer, ":");

At the top, strcat will stop at the first null character, so in this case there will be no harm.

+6
source share

(char *)realloc(buffer, strlen(buffer)* sizeof(char) + (strlen(": ")+1)* sizeof(char));

Must be

(char *)realloc(buffer, (strlen(buffer) + strlen(": ") + 1) * sizeof(char));

isn't that so? You think the string length is incorrect.

0
source share

All Articles