这是我用来在堆上创建char数组的代码
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);
}
当我尝试使用释放它时
for(int c = 0; c< currentArraySize; c++)
free(finalArray[c]); //this gives me invalid ptr error
free(finalArray);
没有memcpy部分,一切都可以,但我使用memcpy破坏了内存。我对c很陌生,无法理解问题的根源
memcpy(copyArray[c], finalArray[c], sizeof(char)*currentArraySize);
最后一个参数最多应为sizeof(char)*6
。