在下 苇名弦一郎 2022-05-02 20:59 采纳率: 100%
浏览 15
已结题

动态内存分配和释放问题!

释放的时候出现了堆损坏 这是为啥?


```c
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdbool.h>
#include <stdio.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    int cnt = 0;
    puts("你要输入几个单词?");
    scanf_s("%d", &cnt);
    char ch = getchar();
    char** pword = (char**)malloc(cnt * sizeof(char*));
    char* ptr = NULL;
    if (!pword)
    {
        puts("分配失败");
        return NULL;
    }
    char temp[5][100];
    size_t lenth = 0;
    for (int i = 0; i < cnt; i++)
    {
        gets_s(temp[i], 100);
        lenth = strnlen(temp[i], 100) + 1;
        printf_s("%d>>%zd \n", i, lenth);
        *(pword + i) = (char*)malloc(lenth * sizeof(char));
        printf_s("%p >>%p \n", *(pword + i), temp[i]);
        strcpy_s(*(pword + i), 100, temp[i]);
        printf_s("%p >>%p \n", *(pword + i), temp[i]);
    }
    for (int i = 0; i < cnt; i++)
    {
        free(*(pword + i));
    }
    free(pword);
    
    return 0;

}

![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/802013694156152.png "#left")



```

  • 写回答

1条回答 默认 最新

  • SmallAntJ 2022-05-02 22:15
    关注

    数组访问越界了,36行分配了lenth长度的内存空间,而strcpy_s(*(pword + i), 100, temp[i]); 里设置的最大长度是100,也就是目标数组长度小于100,结果无法预测,可能会造成缓冲区溢出。
    所以要么改成:

    *(pword + i) = (char*)malloc(100 * sizeof(char));
    

    要么改成:

    strcpy_s(*(pword + i), lenth, temp[i]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月10日
  • 已采纳回答 5月2日
  • 创建了问题 5月2日

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c