这里我们有一个结构体,然后,我们使用 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操作系统实现的
最佳答案
When we populate the string 'abcde' (5 bytes), we overrun the char array inside the struct, which resides on the stack.
不,结构及其关联元素是通过malloc
动态创建的。因此整个结构体(包括 char 数组)都位于堆上。
关于c - 如果我们使用 malloc 分配结构体,那么结构体字段会分配在内存的什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47274977/