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

前端 未结 3 1930
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: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()".

提交回复
热议问题