相关疑难解决方法(0)

可以在其范围之外访问局部变量的内存吗?

我有以下代码.

#include <iostream>

int * foo()
{
    int a = 5;
    return &a;
}

int main()
{
    int* p = foo();
    std::cout << *p;
    *p = 8;
    std::cout << *p;
}
Run Code Online (Sandbox Code Playgroud)

而代码只是运行而没有运行时异常!

输出是 58

怎么会这样?本地变量的内存不能在其功能之外无法访问吗?

c++ memory-management local-variables dangling-pointer

990
推荐指数
19
解决办法
26万
查看次数

是否允许编译器回收释放的指针变量?

有人声称

编译器可以自由地将指针变量重用于其他目的之后 realloc 被释放,所以你不能保证它具有与之前相同的价值

void *p = malloc(42);
uintptr_t address = (uintptr_t)p;
free(p);

// [...] stuff unrelated to p or address

assert((uintptr_t)p == address);
Run Code Online (Sandbox Code Playgroud)

可能会失败.

C11附件J.2读

使用指向通过调用free或realloc函数释放的空间的指针的值(7.22.3)[ 未定义 ]

但附件当然不是规范性的.

附件L.3(规范性的,但可选的)告诉我们,如果

使用指向通过调用free或realloc函数解除分配的空间的指针的值(7.22.3).

结果被允许是关键的未定义行为.

这证实了这一说法,但我希望从标准本身而不是附件中看到适当的引用.

c free pointers standards-compliance compiler-optimization

14
推荐指数
1
解决办法
877
查看次数

比较一个已经空闲的指针调用UB吗?

这似乎是一个相当常见的模式,例如在hexchat中(可能无法编译,另请参阅插件文档.还请注意,这些文档hexchat_plugin_get_info尚未永久使用,因此我为了简单起见省略了它):

static hexchat_plugin *ph;
static int timer_cb(void *userdata) {
    if (hexchat_set_context(ph, userdata)) { /* <-- is this line UB? */
        /* omitted */
    }
    return 0;
}
static int do_ub(char *word[], char *word_eol[], void *userdata) {
    void *context = hexchat_get_context(ph);
    hexchat_hook_timer(ph, 1000, timer_cb, context);
    hexchat_command(ph, "close"); /* free the context - in practice this would be done by another plugin or by the user, not like this, but for the purposes of this example this …
Run Code Online (Sandbox Code Playgroud)

c undefined-behavior hexchat

8
推荐指数
1
解决办法
257
查看次数

为什么 C 函数 free() 不删除值?

我正在学习 C 编程并编写如下基本代码。

我了解到该函数可以释放由等等free()分配的内存。calloc()

但是obj->idobj->name在执行 Object_destroy 后,尽管已执行函数,但仍具有值free()

为什么会出现这种情况?释放内存不等于删除值吗?

#include <stdio.h>
#include <stdlib.h>

typedef struct Object* Object;
struct Object
{
  int id;
  char* name;
};

Object Object_new(int id, char* name)
{
  Object obj = calloc(1, sizeof(struct Object));
  obj->id = id;
  obj->name = name;
  return obj;
}

void Object_destroy(Object obj)
{
  free(obj);
}

int main()
{
  Object obj = Object_new(5, "test");

  printf("%d\n", obj->id); // => 5
  printf("%s\n", obj->name); // => test

  Object_destroy(obj);
  printf("%d\n", …
Run Code Online (Sandbox Code Playgroud)

c malloc free memory-management

3
推荐指数
1
解决办法
1695
查看次数