c调试问题,免费方法
我在 C 程序中遇到问题:
char *str = (char *) malloc(20);
strcpy_s(str, 10, "abcdefghij");
//here I change one byte before str and one byte after
*((int*)str-1) = 10;
*((int*)(str+20)) = 10;
//and it stops on the..
free(str);
调试期间的行 怎么了?
覆盖未分配内存的部分是任务的部分。我知道这通常是不正确的,但在这种情况下它是任务的一部分。
I have the problem in C program:
char *str = (char *) malloc(20);
strcpy_s(str, 10, "abcdefghij");
//here I change one byte before str and one byte after
*((int*)str-1) = 10;
*((int*)(str+20)) = 10;
//and it stops on the..
free(str);
line during the debug
what's wrong?
The part with overwriting not allocated memory is the part of the task. I know that usually it's not correct, but in this context it is the part of the task.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
*((int*)str-1)
通常用于存储分配空间的长度,以便free
知道要释放多少字节...*((int*)str-1)
is often used to store the length of the allocated space, so thatfree
knows how much byte to free...您无法写入
str+20
,因为您只请求了 20 个字节,因此str+19
是您拥有的最后一个字节。str-1
也是如此。You're not allowed to write to
str+20
because you only requested 20 bytes, sostr+19
is the last byte you own. And the same goes forstr-1
.您到底为什么认为您有权更改
str-1
中的任何内容?你没有:)看来你还有另一个问题,由于第一个问题的生动性,我没有注意到这个问题。您可以访问的地址从
str + 0
到str + 19
不等。str + 20
超出了你的范围:)这两件事都会导致所谓的 undefined行为。这意味着您不会对任何行为感到惊讶!包括失败的
free
、调试器崩溃或其他任何情况Why on earth would you think that you have the right to change anything located at
str-1
? You don't :)It appears you have yet another problem, which, because of the vividness of the first one went past my attention. the addresses you may acces vary from
str + 0
tostr + 19
.str + 20
is out of your realm :)Both these things result in what's called undefined behavior. Which means you can't get surprised at any behavior! Including failing
free
, debugger crash, or whatever else写入分配的内存之外的内存会产生未定义的行为。
在这种特殊情况下,我们可以猜测堆管理器可能有一些关于存储在它交给您的内存之前的每个内存块的簿记信息。当您写入分配的块之前的字节时,您将覆盖其中的某些部分,因此它无法再正确释放该块。
Writing to memory outside what you allocated gives undefined behavior.
In this particular case, we can guess that the heap manager probably has some book-keeping information about each block of memory stored just before the memory that it hands to you. When you write to the byte before your allocated block, you're overwriting some part of that, so it can no longer free the block correctly.