错误使用内存集

Wrong use of memset?

本文关键字:内存 错误      更新时间:2023-10-16

有人可以解释一下这里出了什么问题:

class test
{
public:
    char char_arr[100];
};
int main()
{
    test **tq = (test**)calloc(10, sizeof(test*));
    for(unsigned int i = 0; i < 10; i++)
        tq[i] = (test*)calloc(10,  sizeof(test));
    for(unsigned int i = 0; i < 10; i++)
        memset(tq, 0, sizeof(tq[0][0])*100);
    return 0;
}

上面的代码会产生随机崩溃。错误是:"无法写入内存","无法读取内存","堆栈已损坏"

test **tq = (test**)calloc(10, sizeof(test*));
...
for(unsigned int i = 0; i < 10; i++)
    memset(tq, 0, sizeof(tq[0][0])*100);

当你分配tq时,你要求10 * sizeof(test*)字节。但是当你调用memset时,你要求它设置sizeof(tq[0][0]*100)字节。您肯定会写入比分配的更多的字节。也许你的意思是:

for(unsigned int i = 0; i < 10; i++)
    memset(tq[i], 0, 10 * sizeof(test));

这是有道理的,因为:

    tq[i] = (test*)calloc(10,  sizeof(test));

分配 tq[i] 时,分配了 10 * sizeof(test) 个字节。

您将此与 2D 数组混淆:

char x[10][10];

这是一个 2D 数组,可容纳 100 个连续char

但是您已经分配了一堆指针,然后将它们指向每个 10 个字符的单独数组。结果不是连续的;您无法以现有方式访问它。