V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
lhx2008
V2EX  ›  问与答

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

  •  
  •   lhx2008 · 2019-05-12 20:58:32 +08:00 · 887 次点击
    这是一个创建于 1826 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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
    
    wwqgtxx
        1
    wwqgtxx  
       2019-05-12 21:12:05 +08:00 via iPhone   ❤️ 1
    这种算非法访问堆内存吧,具体行为应该是未定义的
    wwqgtxx
        2
    wwqgtxx  
       2019-05-12 21:12:31 +08:00 via iPhone   ❤️ 1
    @wwqgtxx 堆内存->栈内存
    wwqgtxx
        3
    wwqgtxx  
       2019-05-12 21:13:43 +08:00 via iPhone   ❤️ 1
    而且你%p 的时候再取一次地址干嘛
    lhx2008
        4
    lhx2008  
    OP
       2019-05-12 21:16:59 +08:00
    @wwqgtxx 是,这里写的时候没想明白,应该还在栈上
    haiyang416
        5
    haiyang416  
       2019-05-12 21:19:02 +08:00
    ```
    printf("address of in_heap->name = %p \n ", in_heap->name);
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2725 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 04:20 · PVG 12:20 · LAX 21:20 · JFK 00:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.