Home > Net >  Realloc not copying old values
Realloc not copying old values

Time:10-11

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?

CodePudding user response:

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)
  • Related