错误使用内存集
Wrong use of memset?
有人可以解释一下这里出了什么问题:
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 个字符的单独数组。结果不是连续的;您无法以现有方式访问它。
相关文章:
- 内存错误低于在C++年实现埃拉托色尼筛分时的预期
- 将 vector<vector<int>> 传递到函数中会产生内存错误
- 为什么删除分配的阵列会导致内存错误?
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 需要找到3个小错误-内存错误
- 从'deleted function'获取内存错误
- OpenGL, GLFW, GLAD. glViewport(0, 0, 800, 600) 抛出内存错误
- 销毁 std::queue 会导致内存错误
- 加速进程间:管理共享内存错误
- 删除映射中的指针会导致内存错误
- 由于从 std::map 派生的类中的 std::map 迭代器导致的内存错误
- 当我用clang编译代码时,GCOV会出现内存错误
- 查找素数和时出现内存错误
- 循环链表的内存错误:未分配正在释放的指针
- 为什么我会因Valgrind遇到内存错误?(C ,抽象语法树评估)
- 我如何解析包含65k行的代码的文件,导致[BCC32致命错误] F1008出于内存错误
- 动态内存错误
- 内存错误C 私有INT
- 无法在 Mac OS X 上分配内存错误 - java(xx,xx) malloc: *** mmap(size=XX)
- 类对象的可变级别内存错误检测