malloc - C 程序 - 将值 0 分配给 gcc 中的整数
我有一个像这样的链表结构
typedef struct list_node {
int data;
struct list_node *next;
}l_node;
void print_list(l_node *head) {
l_node *cur_node = head;
while(cur_node!=NULL) {
printf("%d\t", cur_node->data);
cur_node = cur_node->next;
}
}
void main() {
printf("List");
l_node *new_node = (l_node*)malloc(sizeof(l_node));
print_list(new_node);
}
当我编译 gcc linkedlist.c 并执行 ./a.out 时 我得到输出 列表 0
但是当我在 VC++ 中尝试时,出现错误(因为我试图访问 cur_node->next 中的无效内存位置)。
那么,gcc的malloc默认为结构体内部的整型变量分配0值吗?为什么我在 gcc 中执行相同的 print_list 时没有得到相同的错误?
I have a linked list structure like this
typedef struct list_node {
int data;
struct list_node *next;
}l_node;
void print_list(l_node *head) {
l_node *cur_node = head;
while(cur_node!=NULL) {
printf("%d\t", cur_node->data);
cur_node = cur_node->next;
}
}
void main() {
printf("List");
l_node *new_node = (l_node*)malloc(sizeof(l_node));
print_list(new_node);
}
When I compile gcc linkedlist.c and do ./a.out
I get output
List
0
But when I tried it in VC++, I got error (since I am trying to access invalid memory location in cur_node->next).
So, does malloc of gcc allocate 0 value by default to the integer variable inside the structure? Why I didn't get the same error while doing the same print_list in gcc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
malloc
返回的内存内容未初始化。在初始化该内存之前(通过至少写入一次),您无法读取该内存。gcc 可能“有助于”对内存进行零初始化,但这种行为不是必需的。 Visual C++ C 运行时 (CRT) 将在发布版本中为您提供未初始化的内存(以实现最佳性能),并在调试版本中为您提供使用特殊填充字节
0xcd
初始化的内存(以帮助您找到可能的位置)使用未初始化的内存)。因此,基本上,您需要在使用内存之前对其进行初始化。如果您希望运行时在将堆块提供给您之前对其进行零初始化,您可以使用
calloc
。The contents of the memory returned by
malloc
are not initialized. You cannot read from that memory before you initialize it (by writing to it at least once).gcc may be "helpfully" zero-initializing the memory, but that behavior isn't required. The Visual C++ C Runtime (CRT) will give you uninitialized memory in a release build (for maximum performance) and memory initialized with the special fill byte
0xcd
in a debug build (to help you find where you may be using uninitialized memory).So, basically, you need to initialize the memory before you use it. If you want the runtime to zero-initialize the heap block before it gives it to you, you may use
calloc
.你需要分配new_node->next = NULL,因为你检查当前节点是否为NULL,而malloc不会用任何值初始化分配的空间,所以不能保证该值会被初始化。为了安全起见,您需要手动将 NULL 分配给链表的尾部,或者无效的指针。
you need to assign
new_node->next = NULL
because you check if the current node is NULL or not, andmalloc
does not initialize the allocated space with any value, so there is no gurantee that the value would be initialized. To be safe you need to assign NULL manually to the tail of the linked list, or an invalid pointer.