我正在 CS50 上做训练任务——一个响应浏览器请求的服务器。我实现了 indexes 函数 - 它被传递到目录的路径 - 类似于:“/home/ubuntu/workspace/pset6/public/” - 我的函数将此路径作为参数并检查目录是否包含 index.php或 .html - 它返回此文件的路径,即 如果没有这样的文件,“/home/ubuntu/workspace/pset6/public/index.html”返回 NULL。
起初我按顺序做了所有事情——一切正常。我决定优化以免重复代码行,将其放入循环中,但现在在循环的第 2 遍,当它到达文件的开头时,出现分段错误。
char* indexes(const char* path)
{
char* index_path = NULL;
FILE* file = NULL;
char* index[2] = {"index.html", "index.php"};
for (int i = 0; i < 2; i++)
{
if (index_path != NULL)
{
free(index_path);
}
index_path = realloc(index_path, strlen(path) + strlen(index[i]) + 1);
strcpy(index_path, path);
strcat(index_path, index[i]);
file = fopen(index_path, "r");
if (file != NULL)
{
fclose(file);
return index_path;
}
}
free(index_path);
return NULL;
}
于是,第二关。
而且他不平等!
释放内存。
index_path指向释放的内存块。我们遇到了麻烦——因为
realloc必须将正确的指针传递给函数。它指向释放的内存块。index_path释放后重置...一般来说 - 你为什么使用
realloc而不是malloc- 因为你释放了内存?只用malloc...