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

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


```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")



```

数组访问越界了,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]);