c - 如果我们使用 malloc 分配结构体,那么结构体字段会分配在内存的什么位置?

标签 c malloc overflow heap-memory

这里我们有一个结构体,然后,我们使用 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 个字节)时,我们超出了结构内的 char 数组,该结构驻留在堆栈上。

  2. 如果我们插入字符串“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/

相关文章:

c - 在 c 中使用 malloc 进行操作时出现段错误

css - 为什么 CSS 宽度为 :100% cause horizontal scrolling?

javascript - 如何让 Mac 平滑滚动以在元素上工作

c - 我如何让它解码(Perl cbc-crypt 到 C cbc_crypt 转换)

c - 正确使用指针

c - 文件 link(device,socket)/dev/fd/need avoid links transition 的 Linux C 问题

c - 指向结构体的指针的二维数组(动态)

c - 为什么在 C 中出现 double free 或 corruption 错误?我释放了我的 mallocs

java - 为什么我的哈希函数收到负值?

c - 用c语言编写字符串程序