Difference between initializing a string with (char *)malloc(0) and NULL

前端 未结 3 1929
Happy的楠姐
Happy的楠姐 2021-01-24 14:52

Why allocating a 0 size char block works in this case? But if I write char *string = NULL; it won\'t work.

I\'m using Visual Studio.



        
相关标签:
3条回答
  • 2021-01-24 15:40

    First let me state, as per the man page of malloc()

    The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

    a call like malloc(0) is valid itself, but then, we need to check the validity of the returned pointer. It can either

    • Return NULL
    • Return a pointer which can be passed to free().

    but anyways, dereferencing that pointer is not allowed. It will cause out-of-bound memory access and cause undefined behaviour.

    That said, two important things to mention,

    1. Please see why not to cast the return value of malloc() and family in C.

    2. Please check the return value of malloc() before using the returned pointer.

    So, to answer your question,

    Difference between initializing a string with (char *)malloc(0) and NULL

    Do not use malloc(0) in this case, as a NULL check on the pointer may fail, giving the wrong impression of a valid allocation of the memory to the pointer. Always use NULL for initialization.

    0 讨论(0)
  • 2021-01-24 15:41

    malloc definition:

    Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

    The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.

    If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.

    Taken from here and found this related question.

    0 讨论(0)
  • 2021-01-24 15:45

    The above code invokes undefined behavior. You have allocated insufficient memory and you are accessing invalid addresses.

    According to the specifications, malloc(0) will return either "a null pointer or a unique pointer that can be successfully passed to free()".

    0 讨论(0)
提交回复
热议问题