Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Realloc not copying old values

When doing my project I’ve came across to a problem. I It seems like realloc is not copying all data from original array. This is what I’m dealing with (code still missing error checking, I know) :

char ** dictionary = (char**) malloc(512  * sizeof(char*));

for (int i = 0; i < 256; i++)
{
    dictionary[i] = (char*) malloc(2 * sizeof(char));
    sprintf(dictionary[i], "%c", i);
}

char * character = dictionary[129];

char ** new_dictionary = realloc(dictionary, 1024);
dictionary = new_dictionary;

char * character2 = dictionary[129];

I first create a array of pointers to char pointers. Then I create pointer to array of chars for each byte and assign byte value. Values of character and character2 differ. Why? I’ve checked for lower and higer indexes (few samples) and the values remains the same. Does this have something to do with that I’m trying to realloc char pointers not just pure data?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is not entirely clear what you are trying to do.
I assume you want to increase the memory and expect realloc to copy the content of the initial memory block.

This will not happen in your code:

char ** dictionary = (char**) malloc(512  * sizeof(char*));
...
char ** new_dictionary = realloc(dictionary, 1024);
dictionary = new_dictionary;

char * character2 = dictionary[129];

You are actually shrinking your memory size.
Initialliy you reserve memory for 512 pointers. Then you resize to 1024 bytes. On a 64 bit system that will only be sufficient for 128 pointers.
As a result, dictionary[129] is an out of bounds access.

You probably wanted to resize this way:

realloc(dictionary, 1024 * sizeof *dictionary)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading