我有一个项目,我创建了一个存储单词的 2D 字符数组,可以选择添加更多单词,然后在必要时调整数组大小。当我尝试使用它并修复它时,我遇到了各种错误,所以现在我认为我需要在我的代码上多看一些眼睛。我专门在寻找任何明显突出为分配内存或初始化数组的错误或麻烦方式的东西。
我特定于此代码的错误说"free():无效指针"并导致 SIGABRT。下面是我的代码。
这是我的调整大小功能。
char ** resize_array(char **array)
{
int i;
char** tmp = malloc(2 * sizeof(*array));
int j;
for(j = 0; j < (2 * sizeof(*array)); j++)
tmp[j] = malloc(2 * sizeof(*array));
for(i = 0; i < (sizeof *words); i++)
{
strcpy(tmp[i], words[i]);
}
for(i = 0; words[i] != NULL; i++)
free(words[i]);
free(words);
return tmp;
}
这是我正在实现的调整大小函数
int len;
len = (sizeof words);
if(upperbound > len) //upperbound keeps track of the word count
//and resizes the array
{
char **tmp = resize_array((char **) words);
int i;
for(i = 0; i <= upperbound; i++)
strcpy(words[i], tmp[i]);
}
最后是最初初始化的"words"数组。
char words[14][50];
我正在使用VI并在Ubuntu上运行所有内容,仅供参考。提前感谢大家的帮助!
在 resize_array
函数中,不能仅使用指向数组的指针来确定数组的先前大小。
对马洛克的呼唤
malloc(2 * sizeof(*array))
请求分配大小为指向 char 的指针大小的两倍(在 64 位计算机上只有 16 个字节)。
这是您需要解决的第一个问题。