首页 文章

如果我们使用malloc分配struct,那么内存中是否分配了struct字段? [关闭]

提问于
浏览
-4

这里我们有一个struct,然后,我们用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;

据我所知,到目前为止 . 这些肯定是否正确?

  • 当我们填充字符串'abcde'(5个字节)时,我们溢出了存在于堆栈中的struct内的char数组 .

  • 如果我们插入字符串'abcdefghi'(9字节),我们会超出结构本身,我假设它在堆上 . 但是我们也超出了堆栈上的char数组 .

Edit :为了更准确,这个问题基于C99标准,由i686 O.S实现 .

2 回答

  • 0

    当我们填充字符串'abcde'(5个字节)时,我们溢出了结构中的char数组,该数组驻留在堆栈上 .

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

  • -1

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

相关问题