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
1
wwqgtxx 2019-05-12 21:12:05 +08:00 via iPhone 1
这种算非法访问堆内存吧,具体行为应该是未定义的
|
3
wwqgtxx 2019-05-12 21:13:43 +08:00 via iPhone 1
而且你%p 的时候再取一次地址干嘛
|
5
haiyang416 2019-05-12 21:19:02 +08:00
```
printf("address of in_heap->name = %p \n ", in_heap->name); ``` |