lhx2008
V2EX  ›  问与答

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

  •  
  •   lhx2008 · May 12, 2019 · 1350 views
    This topic created in 2602 days ago, the information mentioned may be changed or developed.

    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  
       May 12, 2019 via iPhone   ❤️ 1
    这种算非法访问堆内存吧,具体行为应该是未定义的
    wwqgtxx
        2
    wwqgtxx  
       May 12, 2019 via iPhone   ❤️ 1
    @wwqgtxx 堆内存->栈内存
    wwqgtxx
        3
    wwqgtxx  
       May 12, 2019 via iPhone   ❤️ 1
    而且你%p 的时候再取一次地址干嘛
    lhx2008
        4
    lhx2008  
    OP
       May 12, 2019
    @wwqgtxx 是,这里写的时候没想明白,应该还在栈上
    haiyang416
        5
    haiyang416  
       May 12, 2019
    ```
    printf("address of in_heap->name = %p \n ", in_heap->name);
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2819 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 12:54 · PVG 20:54 · LAX 05:54 · JFK 08:54
    ♥ Do have faith in what you're doing.