这段 C 代码底层发生了什么?

2019-05-12 20:58:32 +08:00
 lhx2008

name 是否是在离开作用域时由编译器重新分配了内存?是在哪个区域分配了空间?这样的行为是未定义的吗?

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

typedef struct {
  const char*  name;
} island;

int main() {
  island *in_heap =  (island*) malloc(sizeof(island));
  {
    char name[80];
    fgets(name, 80, stdin);
    in_heap->name = name;
    fgets(name, 80, stdin);
    printf("address of name in scope = %p \n", &name);
  }
  printf("\nout of scope \n");
  printf("name is not deleted, name = %s", in_heap->name);
  printf("address of in_heap->name = %p \n  ", &(in_heap->name));
  free(in_heap);
}

输入

test
test2

输出

address of name in scope = 0x7ffffce79b10

out of scope
name is not deleted, name = test2
address of in_heap->name = 0x7ffff5954260
890 次点击
所在节点    问与答
5 条回复
wwqgtxx
2019-05-12 21:12:05 +08:00
这种算非法访问堆内存吧,具体行为应该是未定义的
wwqgtxx
2019-05-12 21:12:31 +08:00
@wwqgtxx 堆内存->栈内存
wwqgtxx
2019-05-12 21:13:43 +08:00
而且你%p 的时候再取一次地址干嘛
lhx2008
2019-05-12 21:16:59 +08:00
@wwqgtxx 是,这里写的时候没想明白,应该还在栈上
haiyang416
2019-05-12 21:19:02 +08:00
```
printf("address of in_heap->name = %p \n ", in_heap->name);
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/563425

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX