user2653179
user2653179

Reputation: 423

Heap Corruption Detected: after Normal block

"CRT detected that the application wrote to memory end of heap buffer" error. It crashes when it arrives to free. Any help is appreciated.

int messageFunction(char* message) {
   char* sPtr = strstr(message,"Subject:");
   char* cPtr = strstr(message,"Content:");

   char* messageSubject = (char*) malloc(cPtr - sPtr - strlen("Subject:"))
   char* messageContent = (char*) malloc(strlen(cPtr + strlen("Content:")))

   strncpy(messageSubject, 
          stPtr + strlen("Subject:"), 
          cPtr - sPtr - strlen("Subject:"));

   messageSubject[cPtr - sPtr - strlen("Subject:")] = '\0';

   strncpy(messageContent, 
           cPtr + strlen("Content:"), 
           strlen(cPtr + strlen("Content:")));
   ...
   free(messageSubject);
   free(messageContent);
   }


void main() {
  char* message = "Subject:HelloWorldContent:MessageContent";
  int result = messageFunction(message);
 }

Upvotes: 5

Views: 30645

Answers (2)

tinman
tinman

Reputation: 6608

You are allocating memory that is one byte too short. Your calculations are for the length of the data between e.g. "Subject:" and "Content:" but do not take into account the need for a null terminator in the string. Then when you manually add the null terminator you are invoking undefined behaviour by writing past the end of the array.

Changing your code to the following should fix it.

char* messageSubject = malloc(cPtr - sPtr - strlen("Subject:") + 1)
char* messageContent = malloc(strlen(cPtr + strlen("Content:")) + 1)

You also do not show the code in the "..." section, so you may have an unterminated string in there that if it is being processed by the string library routines could cause problems.

Upvotes: 14

rici
rici

Reputation: 241731

If you do this:

char* v = malloc(n);

then valid subscripts of v range from v[0] to v[n-1]. In particular, v[n] is never valid. That's a general rule. If you look at your code again, you should see the problem.

A couple of notes:

  1. Your code assumes the Subject: comes before the Content: and that both of them exist. This assumption will fail to be correct in some case. You should check before you start malloc'ing huge amounts of memory (since small negative numbers turn into huge positive unsigned numbers). You should also make sure your mallocs don't return 0, instead of segfaulting when they do.

  2. strdup (and strndup) will often save you from embarrassing "oops, I didn't allocate enough room for the NUL byte" errors. They also don't require nearly as much futzing around, making your code simpler, more reliable, and easier to understand. Get to know them. They will be your friends.

  3. If nothing else works, valgrind can help you find bugs like this.

Upvotes: 0

Related Questions