C - 释放数组时检测到堆损坏

C - Heap Corruption Detected when freeing array

进行赋值,必须动态分配一个指针数组,然后在函数结束时释放它。 问题是当我释放数组时,它给了我一个 "Heap Corruption Detected" 错误,我无法弄清楚为什么会这样。 有人能在这里看到什么吗? 它说我在分配的内存结束后写入,但我不明白为什么。

typedef struct _client
{
    char id[9];         
    char phone[12]; 
} Client;

Short_client *createShortClientArr(int n)
{
    Client *arr = (Client *)malloc(n * sizeof(Client));
    char garbage;
    garbage = getc(stdin);//for getting the '\n' from the last input
    for (int i = 0; i < n; i++)
    {
        fgets(arr[i].id, 9, stdin);
        arr[i].id[9] = '[=10=]';
        garbage = getc(stdin);
        fgets(arr[i].phone, 12, stdin);
        arr[i].phone[12] = '[=10=]';
        garbage = getc(stdin);
    }
free(arr);
}

当您释放内存时,Windows 还将检查您是否写入了数组末尾。既然你这样做了,它就会抛出这个异常,让你知道你有一个错误。

 char phone[12]; 

这将创建一个索引为 0-11 的数组。

    arr[i].phone[12] = '[=11=]';

12 不是该数组的有效索引,因此这会将 '[=12=]' 写入数组末尾的 char 中。您的其他阵列也有同样的错误。