求助:exe 已触发了一个断点,有未经处理的异常: 0xC0000374: 堆已损坏。 (参数: 0x77614270)。

qq_29289253 2018-01-08 12:07:05
以下程序调试中发现结果能出来,但每次都会触发断点,并且提示堆损坏。
自我感觉是内存分配或读取错误,但不知道怎么改,请指导,谢谢。



char* change(char *str)
{
char *tempstr = malloc(strlen(str) + 1);
//memset(tempstr, 0, sizeof(str) + 1);
int x=0, y=0;
char ascii_1, ascii_2;
while (tempstr[x])
{
/*printf("x=%d\n", x);
printf("y=%d\n", y);*/
if ((tempstr[x] = str[y]) == '%')
{
if (str[y + 1] >= 'A')
{
ascii_1 = str[y + 1] - 55;

}
else
{
ascii_1 = str[y + 1] - 48;
}
if (str[y + 2] >= 'A')
{
ascii_2 = str[y + 2] - 55;

}
else
{
ascii_2 = str[y + 2] - 48;

}
tempstr[x] = ascii_1 * 16 + ascii_2;
y += 2;

}
x++;
y++;

}
/*printf("x=%d\n", x);
printf("y=%d\n", y);*/
tempstr[x] = '\0';

//printf("%s\n", tempstr);


return tempstr;

}


void main()
{
char str[128] = "%D6%DC%C8%BA%BA%A3";


printf("%s", change(str));

system("pause");




}




...全文
866 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
真相重于对错 2018-01-08
  • 打赏
  • 举报
回复
while (tempstr[x]) ==》 while (str[y]!='\0')
真相重于对错 2018-01-08
  • 打赏
  • 举报
回复
在change函数里,对tempstr 操作越界了!
paschen 2018-01-08
  • 打赏
  • 举报
回复
你访问堆内存越界了,可以单步跟踪程序运行查看
qq_29289253 2018-01-08
  • 打赏
  • 举报
回复
谢谢指导,明白了
自信男孩 2018-01-08
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* change(char *str)
{
    char *tempstr = (char *)malloc(strlen(str) + 1);
    //memset(tempstr, 0, sizeof(str) + 1);
    int i = 0, j = 0;
    char ascii_1, ascii_2;
    while (str[i])
    {
        printf("%c\n", str[i]);
        if (str[i] == '%') {
            if (str[i+1] >= 'A')
                ascii_1 = str[i+1] - 'A';
            else
                ascii_1 = str[i+1] - '0';

            if (str[i+2] >= 'A')
                ascii_2 = str[i+2] - 'A';
            else
                ascii_2 = str[i+2] - '0';

            tempstr[j] = ascii_1 * 16 + ascii_2;
            i += 2;
            j++;
        } else {
            i++;
        }
        /*
        if ((tempstr[x] = str[y]) == '%')
        {
            if (str[y + 1] >= 'A')
            {
                ascii_1 = str[y + 1] - 55;

            }
            else
            {
                ascii_1 = str[y + 1] - 48;
            }
            if (str[y + 2] >= 'A')
            {
                ascii_2 = str[y + 2] - 55;

            }
            else
            {
                ascii_2 = str[y + 2] - 48;

            }
            tempstr[x] = ascii_1 * 16 + ascii_2;
            y++;
        }
        x++;
        */

    }
    /*printf("x=%d\n", x);
      printf("y=%d\n", y);*/
    tempstr[j] = '\0';

    //printf("%s\n", tempstr);


    return tempstr;

}


int main()
{
    char str[128] = "%D6%DC%C8%BA%BA%A3";

    printf("%s", change(str));
    system("pause");

    return 0;
}
参考一下吧

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧