代码之家  ›  专栏  ›  技术社区  ›  another

如果我们用malloc分配struct,那么在内存中分配了哪些struct字段?[已关闭]

  •  -4
  • another  · 技术社区  · 7 年前

    这里我们有一个结构,然后用malloc分配它的一个实例:

    typedef struct _MyStruct {
        struct *nextStruct;
        char array[4];
    } MyStruct
    
    /* Allocates space on heap for the struct */
    _MyStruct *m = malloc(sizeof(MyStruct));
    printf("%zu bytes\n", sizeof(MyStruct)); /* Outputs: 8 bytes */
    
    int r;
    
    /* We intentionally overflow the buffer inside of the struct */
    r = (int)gets(m->array); /* Input */
        if (r == 0)
             return;
    

    根据我目前所了解的情况。这些肯定正确吗?

    1. 当我们填充字符串“abcde”(5字节)时,我们会溢出位于堆栈上的结构内部的字符数组。

    2. 如果我们插入字符串“abcdefghi”(9字节),我们就会溢出结构本身,我假设它在堆上。但我们也会溢出堆栈上的char数组。

    编辑 :更准确地说,这个问题基于C99标准,由i686 O.S.实现。

    2 回复  |  直到 7 年前
        1
  •  0
  •   MFisherKDX    7 年前

    当我们填充字符串“abcde”(5字节)时,我们会溢出位于堆栈上的结构内部的字符数组。

    不,结构及其相关元素是通过动态创建的 malloc . 所以整个结构,包括char数组都位于堆上。

        2
  •  -1
  •   Unh0lys0da    7 年前

    您正在覆盖堆上结构的地址,而不是堆上的结构本身,假设您指的是指向下一个结构的指针