堆损坏检测:普通块之后 [英] Heap Corruption Detected: after Normal block

查看:122
本文介绍了堆损坏检测:普通块之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CRT检测应用程序写信给堆缓冲区的内存结束错误。它崩溃,当它到达免费。任何帮助是AP preciated。

  INT messageFunction(字符*消息){
   字符*特征码=的strstr(消息,主题:);
   字符* CPTR =的strstr(消息,内容:);   字符* messageSubject =(字符*)malloc的(CPTR - 特征码 - 的strlen(主题:))
   字符* = messageContent的(字符*)malloc的(strlen的(CPTR + strlen的(内容)))   函数strncpy(messageSubject,
          stPtr + strlen的(主题:),
          CPTR - 特征码 - 的strlen(主题:));   messageSubject [CPTR - 特征码 - strlen的(主题:)] ='\\ 0';   函数strncpy(messageContent中,
           CPTR + strlen的(内容),
           strlen的(CPTR + strlen的(内容)));
   ...
   免费(messageSubject);
   免费(messageContent中);
   }
无效的主要(){
  字符*消息=主题:HelloWorldContent:在messageContent
  INT结果= messageFunction(消息);
 }


解决方案

您的分配内存是一个字节太短。你的计算是例如间的数据的长度主题:和内容,但不考虑字符串的空终止的需要。然后,当你通过写过去的数组的末尾添加要调用未定义行为空终止符。

更改code以下应该修复它。

 的char * messageSubject =的malloc(CPTR  - 特征码 - 的strlen(主题:)+ 1)
字符* = messageContent中的malloc(strlen的(CPTR + strlen的(内容))+ 1)

您还没有显示的...部分中的code,所以你可能有一个未终止的字符串在那里,如果它正在被串库函数处理可能导致问题。

"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);
 }

解决方案

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.

这篇关于堆损坏检测:普通块之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆