Do I need to initiallize(set to 0) memory after calling realloc?

前端 未结 3 1485
不知归路
不知归路 2020-12-19 17:20

I need to implement a simple dynamic array of pointers to a typedef\'ed pointer.
Using realloc each time it\'s requested by the user, the array size will grow by sizeof(

3条回答
  •  没有蜡笔的小新
    2020-12-19 17:51

    Be aware that the null-pointer does not have to be equal to a literal 0 in C. It is merely guaranteed to not be equal to any valid pointer. Furthermore, null-pointers are technically allowed to be different for different pointer types (e.g. function-pointers vs. char-pointers).

    Therefore, simply initialising the memory to zero could invoke undefined behaviour.

    So initiallizing to NULL, would be correct! That's what I've done! – Chris

    No, what you would have to do is cast the null like this: (void*)NULL, and write this to the memory location. But you never actually write to the memory you malloc (via passing NULL to realloc). You're basically just reading uninitialised memory (which is undefined behaviour) in your printf.

提交回复
热议问题