免费双重免费或损坏错误

时间:2015-03-04 03:22:32

标签: c malloc free memcpy

这是我用来在堆上创建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很新,我无法理解问题的根源

1 个答案:

答案 0 :(得分:2)

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

最后一个参数最多应为sizeof(char)*6