c调试问题,免费方法

发布于 2024-10-21 02:04:49 字数 324 浏览 4 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

墨落画卷 2024-10-28 02:04:50

*((int*)str-1) 通常用于存储分配空间的长度,以便 free 知道要释放多少字节...

*((int*)str-1) is often used to store the length of the allocated space, so that free knows how much byte to free...

绿萝 2024-10-28 02:04:49

您无法写入 str+20,因为您只请求了 20 个字节,因此 str+19 是您拥有的最后一个字节。 str-1 也是如此。

You're not allowed to write to str+20 because you only requested 20 bytes, so str+19 is the last byte you own. And the same goes for str-1.

夜雨飘雪 2024-10-28 02:04:49

您到底为什么认为您有权更改 str-1 中的任何内容?你没有:)

看来你还有另一个问题,由于第一个问题的生动性,我没有注意到这个问题。您可以访问的地址从 str + 0str + 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 to str + 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

你怎么敢 2024-10-28 02:04:49

写入分配的内存之外的内存会产生未定义的行为。

在这种特殊情况下,我们可以猜测堆管理器可能有一些关于存储在它交给您的内存之前的每个内存块的簿记信息。当您写入分配的块之前的字节时,您将覆盖其中的某些部分,因此它无法再正确释放该块。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文