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
1.3k views
in Technique[技术] by (71.8m points)

c - 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:")] = '';

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


void main() {
  char* message = "Subject:HelloWorldContent:MessageContent";
  int result = messageFunction(message);
 }
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 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.


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

...