gpt4 book ai didi

c - 当输入地址指向无效地址时,realloc 崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:51 25 4
gpt4 key购买 nike

realloc 可能返回相同的输入地址或不同的地址。如果它返回不同的地址,则它应在内部取消分配/释放输入内存并将该内容移动到另一个位置并返回该新地址。

请考虑以下情况。

new_ptr = realloc (2000, 10000)  // Lets assume the input address is 2000 

// Lets assume the new_ptr address is 3000

因此,内部 realloc 应释放指针指向 2000 的内存并将这些数据移动到新位置 3000 并返回 3000 地址。

现在地址 2000 指向无效。因此,它不会被 realloc API 分配给 NULL。

现在,将该无效地址传递给 realloc 函数。实时可能会发生变化,realloc 可能会得到无效的输入地址。

new_ptr = realloc(2000, 10000)

此 2000 地址无效,因为它已被先前的 realloc 释放。现在程序崩溃了。

我可以通过以下方式解决这个问题吗?

      if (new_ptr != old_ptr ) {
old_ptr = NULL;
}

因为 old_ptr 无效。我会将它分配给 NULL。请确认我的更正。

最佳答案

想想你的第一句话:

realloc may return either the same input address or a different address.

这意味着您可以只使用返回值作为您的新指针,您不必知道它是否与您之前的值不同。如果不同,realloc() 已经为您释放了前一个 block 。

但有一个异常(exception):如果分配失败,realloc() 可能会返回 0/NULL只有在这种情况下,旧指针仍然有效。因此,正确使用 realloc() 的常见用法如下所示:

T *x = malloc(x_size);
// check x for NULL

// [...]

T *tmp = realloc(x, new_size);
if (!tmp)
{
free(x);
// handle error, in many cases just exit(1) or similar
}
x = tmp; // use the new pointer, don't care whether it's the same

请注意,根据 C 标准,在 成功 调用 realloc() 之后使用 x(来 self 上面的示例)是未定义的, x调用后无效。这不会告诉您有关 x 实际值的任何。它只是告诉您“不要使用它,否则您的程序可能会做任何事情”。

这段自述可能会帮助您理解未定义的行为的含义:

Undefined behavior in C

C is a very low-level language and one consequence of that is the following:

Nothing will ever stop you from doing something completely wrong.

Many languages, especially those for some managed environment like Java or C# actually stop you when you do things that are not allowed, say, access an array element that does not exist. C doesn't. As long as your program is syntactically correct, the compiler won't complain. If you do something forbidden in your program, C just calls the behavior of your program undefined. This formally allows anything to happen when running the program. Often, the result will be a crash or just output of "garbage" values, as seen above. But if you're really unlucky, your program will seem to work just fine until it gets some slightly different input, and by that time, you will have a really hard time to spot where exactly your program is undefined. Therefore avoid undefined behavior by all means!.

On a side note, undefined behavior can also cause security holes. This has happened a lot in practice.

关于c - 当输入地址指向无效地址时,realloc 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45206528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com