如果我们使用 malloc 分配结构体,那么结构体字段分配在内存的什么地方?
Where on memory are struct fields allocated if we allocate struct with malloc?
这里我们有一个结构,然后,我们用 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 个字节)时,我们超出了驻留在堆栈中的结构中的 char 数组。
如果我们插入字符串 'abcdefghi'(9 个字节),我们就会超出结构本身,我假设它在堆上。但是我们也溢出了堆栈上的 char 数组。
编辑:更准确的说,这道题是基于C99标准,由一个i686实现的O.S。
When we populate the string 'abcde' (5 bytes), we overrun the char array inside the struct, which resides on the stack.
不,结构及其关联元素是通过 malloc
动态创建的。所以整个结构,包括 char 数组都在堆上。
你正在覆盖堆上结构的地址,而不是堆上的结构本身,假设你指的是指向下一个结构的指针
这里我们有一个结构,然后,我们用 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 个字节)时,我们超出了驻留在堆栈中的结构中的 char 数组。
如果我们插入字符串 'abcdefghi'(9 个字节),我们就会超出结构本身,我假设它在堆上。但是我们也溢出了堆栈上的 char 数组。
编辑:更准确的说,这道题是基于C99标准,由一个i686实现的O.S。
When we populate the string 'abcde' (5 bytes), we overrun the char array inside the struct, which resides on the stack.
不,结构及其关联元素是通过 malloc
动态创建的。所以整个结构,包括 char 数组都在堆上。
你正在覆盖堆上结构的地址,而不是堆上的结构本身,假设你指的是指向下一个结构的指针