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