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

前端 未结 3 1441
不知归路
不知归路 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:43

    Well, it all depends. Do you require that the memory be initialized to 0? If not, then no, you don't need to do anything. Just as is the case with malloc, realloc doesn't perform any initialization. Any memory past the memory that was present in the original block is left uninitialized.

    0 讨论(0)
  • 2020-12-19 17:43

    Going by the definition of realloc()

    realloc(void *p, size_t size) changes the size of the object pointed to by p to size. The contents will be unchanged up to the minimum of the old and new sizes. If the new size is larger, the new space is uninitialized. (from Kernighan and Ritchie)

    You may have to initialize the new space. You can do that when it is decided what kind of data the address pointed to by the void* will hold.

    0 讨论(0)
  • 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.

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