-1

this is the piece of code i use to create my char array on heap

int currentArraySize = 10;
char **finalArray = malloc(sizeof(char*)*currentArraySize);
char buf[6] = "hello";
for(int b=0; b<currentArraySize; b++ )
{
    char * tmpString = (char*)malloc(sizeof(char)*6);
    //copy the contents of buf to newly allocated space tmpString
    strncpy(tmpString,buf,6);
    finalArray[b] = tmpString;
}

//this should be a deep copy of finalArray
char **copyArray = malloc(sizeof(char*)*currentArraySize);
for(int c=0; c<currentArraySize; c++)
{
    copyArray[c] = (char*)malloc(sizeof(char*)*6);
    //this supposed to copy the contents of finalArray[c] to copyArray[c] right?
    memcpy(copyArray[c], finalArray[c], sizeof(char)*currentArraySize);
}

and when i try to free it using

for(int c = 0; c< currentArraySize; c++)
    free(finalArray[c]); //this gives me invalid ptr error
free(finalArray);

Without the memcpy part, everything is OK, but I'm somehow corrupting the memory using memcpy. I'm quite new to c, and i couldn't understand the root of the problem

epipav
  • 339
  • 2
  • 14
  • I'm pretty sure that you're corrupting memory, but those two code snippets don't have the problem. I suggest changing all the `5`s to `6`s, and change the second `malloc` to `char *tmpString = malloc( 6 );`. – user3386109 Mar 04 '15 at 03:34
  • `malloc(sizeof(char*)*6)` is wrong because it should be `sizeof(char)`. – John Zwinck Mar 04 '15 at 04:01
  • thats just another typo by me when writing the code to SO. I'm still getting the double free error – epipav Mar 04 '15 at 04:03
  • @epipav The answer from timrau is correct. The size in the `memcpy` should just be `6`. Note that you don't need `sizeof(char) * 6`, since the C language defines `sizeof(char)` to be `1`. – user3386109 Mar 04 '15 at 04:08

1 Answers1

2
memcpy(copyArray[c], finalArray[c], sizeof(char)*currentArraySize);

The last parameter should be at most sizeof(char)*6.

timrau
  • 22,578
  • 4
  • 51
  • 64