开发者

malloc - C program - allocates value 0 to integer in gcc

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?


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.


you need to assign new_node->next = NULL because you check if the current node is NULL or not, and malloc 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜