英文:
What will happen if I malloc a pointer of a struct datatype which contains an element of a pointer of another datatype?
问题
考虑以下代码:
typedef struct list_ele
{
char *value;
struct list_ele *next;
} list_ele_t;
typedef struct
{
list_ele_t *head;
int qSize;
} queue_t;
如果我使用函数来为queue_t
类型的指针分配内存,就像这样:
queue_t *q = malloc(sizeof(queue_t));
实际上会发生什么?我的意思是,malloc
将创建多大的内存,我是否应该使用以下代码:
q->head = malloc(sizeof(list_ele_t));
来为q->head
申请空间?
我不擅长C语言(;w;),我尽力思考了但什么也没得到。
英文:
Consider the following code:
typedef struct list_ele
{
char *value;
struct list_ele *next;
}list_ele_t;
typedef struct
{
list_ele_t *head;
int qSize;
}queue_t;
And If I use a function to malloc a pointer of queue_t like this
queue_t *q = malloc(sizeof(queue_t));
What it actually happen? I mean, how big the memory it will create by malloc, should I use the following code
q->head = malloc(sizeof(list_ele_t));
to apply for space for q->head?
I'm not good at C language (;w;) , I try my best to think but I got nothing.
答案1
得分: 1
一个C指针通常!!!是8个字节,所以当你执行以下操作时:
queue_t *q = malloc(sizeof(queue_t));
你分配了8个字节(指针)+ 4个字节(整数)+ 4个字节(填充,见下文)(通常)的内存,然后你让q
指向它。由于你还没有为q->head
分配任何内容,q->head
将指向随机的内存位置。当你执行以下操作时:
q->head = malloc(sizeof(list_ele_t));
你分配了8个字节 + 8个字节(通常)的内存,然后将q->head
指向它。此外,了解一下结构填充是什么:
sizeof(queue_t) -> 16
sizeof(list_ele_t) -> 16
因此,实际上你为q
指向的内存分配了超过12个字节。
英文:
A C pointer is usually!!! 8 bytes so when you do
queue_t *q = malloc(sizeof(queue_t));
you allocate 8(pointer) + 4(int) + 4(padding, see bellow) (usually) bytes of memory and you have q
point to it. q->head
is going to point to a random location as you have not assigned anything to it. Of course when you do
q->head = malloc(sizeof(list_ele_t));
you allocate 8 + 8 (usually) bytes of memory and you point q->head to it. Also learn what structure padding is:
sizeof(queue_t) -> 16
sizeof(list_ele_t) -> 16
So you actually allocate more than 12 bytes for the memory that q points to.
答案2
得分: 1
栈 | 堆
|
q ----------|---> +------------+
| + 一块内存 +
| + 大小等于 +
| + queue_t +
| + 结构体 +
| +------------+
(指向 queue_t | / \
结构体的指针) | / \
| / \
| qsize head
| |
| |
| |
| +-----------+
| + 一块大小为 +
| + size list +
| + 的内存 +
| +-----------+
|
附注:
- 通过
malloc
分配的存储是未初始化的。 malloc
通过返回NULL
指针值来指示失败。- 对于每次分配,都必须有一个对应的
free
。
英文:
Stack | Heap
|
q ----------|---> +------------+
| + A chunk of +
| + memory +
| + equal to +
| + sizeof +
| + queue_t +
(a pointer to | +------------+
a struct of | / \
type queue_t) | / \
| / \
| qsize head
| |
| |
| |
| +-----------+
| + Chunk of +
| + memory of +
| + size list +
| +-----------+
|
Side Notes:
-
The storage that is allocated through
malloc
is uninitialized. -
malloc
indicates failure by returning aNULL
pointer value. -
For every allocation, there must be a
free
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论