Seung Min Lee
Seung Min Lee

Reputation: 31

realloc twice doesn't work on visual studio

Can you tell me why this doesn't work on Visual Studio?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main()
{

    //dynamic memory allocation
     char** document = (char**)malloc(sizeof(char*));

    //lets increase the double pointer document's size. now it has document[0] and document[1]
    document = (char**)realloc(document, 2 * sizeof(char*));

    //now let's increase the size of the document[1] to twice bigger so that it will have document[1][0] and document[0][0] 
    document[1] = (char*)realloc(document[1], 2 * sizeof(char)); // this give error.

}

Upvotes: 0

Views: 240

Answers (1)

walnut
walnut

Reputation: 22152

You did not assign any value to document[1] before you called realloc(document[1], 2 * sizeof(char));. The additional memory that realloc allocates is not initialized to any value.

Therefore the value of document[1] will be indeterminate at this point and using indeterminate values in most situations causes undefined behavior.

Anyway, even if the value wasn't indeterminate, you can only pass a pointer that was returned from malloc, calloc or realloc or a null pointer value to realloc. Otherwise, again, your program has undefined behavior.

While document's value is a pointer returned by malloc/realloc, document[1]'s value is certainly not a pointer returned by either of the mentioned functions or a null pointer, because you didn't assign either of these to it.

To make what you are trying to do work, you need to either set document[1] to NULL before the realloc call (in which case realloc will behave like malloc) or use malloc instead. Given that the first variant would be just a more complex way of writing the latter, I suggest you just use malloc.

Upvotes: 3

Related Questions