我发布了一个问题并得到了答案 here . 这是我在 VC2010 上调试的代码。我得到最后显示的运行时错误。 sdir 的使用有什么问题?
#include<iostream>
#include<stdlib.h>
#include<windows.h>
void make_dir(int depth, char *dir) {
if (depth < 3) {
CreateDirectoryA (dir,NULL);
for (int i = 0; i < 10; i++) {
char *sdir= (char*)malloc(strlen(dir+10)); // XXX 10?
strcpy(sdir, dir);
sprintf(sdir + strlen(sdir), "\\%d", i);
printf("%s\n", sdir);
CreateDirectoryA(sdir,NULL);
make_dir(depth + 1, sdir);
free(sdir);
}
}
}
int main()
{
make_dir(0,"dir");
return 1;
}
错误是:
HEAP[mkdir.exe]: Heap block at 004114E8 modified at 00411514 past requested size of 24 Windows has triggered a breakpoint in mkdir.exe.
This may be due to a corruption of the heap, which indicates a bug in mkdir.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while mkdir.exe has focus.
The output window may have more diagnostic information. The program '[3008] mkdir.exe: Native' has exited with code 0 (0x0).
最佳答案
我看到的最明显的错误是您将 10 添加到传递给 strlen
的指针;如果字符串长度小于 10 个字符,这将读取字符串外部的内存,否则从字符串的长度中减去 10。您可能希望将 10 添加到 strlen
的结果,而不是输入。
换句话说,将 +10
之后的 )
移动到 +10
之前。
关于c - 堆的以下代码损坏是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9544228/