这是我程序的一部分。parameters.path
是一个字符串,包含我将要使用的文件的路径,但这不是此代码中的。
typedef struct directory {
char *name;
char *path;
} directory;
void insertDir(directory*** array , char * path, char* name, int* length) {
directory *p = malloc(sizeof(directory));
p->path = malloc(strlen(path)+ 1);
strcpy(p->path, path);
p->name = malloc(strlen(name)+ 1);
strcpy(p->name, name);
*array = (directory**) realloc( *array , (*length) * (sizeof(directory*)));
*array[(*length)] = p;
(*length)++;
}
int main(int argc , char** argv) {
directory** array = NULL;
int lenght = 0;
while(true) {
insertDir(&array, parameters.path, name , &lenght);
}
return 0;
}
它在第三个realloc
上失败,并带有分割故障。你能帮我吗?
执行realloc()
时,您需要在长度上添加1个,因为您还没有增加。
*array = realloc( *array , (*length + 1) * (sizeof(directory*)));
您还需要更改:
*array[(*length)] = p;
to:
(*array)[*length] = p;
因为订阅操作员的优先级高于解雇操作员。请参阅此处的C操作员优先表。[]
中也不需要括号。
除了 (*array)[*length]
索引问题外,您还可以通过malloc
和realloc
的几个分配失败而开放。首先,通常,始终验证您的分配成功。说了足够。
接下来,使用realloc
,最好使用temporary
变量而不是数组重新分配。如果重新分配失败,则realloc
返回NULL
,使您完全失去了array
的地址。这将导致所有现有数据的丢失。相反,如果您使用tmp
指针进行重新分配,则可以以优雅的方式处理故障,并且能够free
最初分配给array
的内存块。
这是处理分配/重新分配的更强大方法。注意:您要代码对重新分配失败的响应:
void insertDir (directory*** array, char *path, char *name, int *length)
{
directory *p = malloc (sizeof *p);
if (!p) {
fprintf (stderr, "error: virtual memory exhausted.n");
exit (EXIT_FAILURE);
}
p->path = malloc (strlen (path) + 1);
strcpy (p->path, path);
p->name = malloc (strlen (name) + 1);
strcpy(p->name, name);
directory **tmp = realloc (*array, (*length + 1) * sizeof *tmp);
if (!tmp) {
fprintf (stderr, "error: struct reallocation failure.n");
exit (EXIT_FAILURE);
}
*array = tmp;
(*array)[*length] = p;
(*length)++;
}