gpt4 book ai didi

调用 free() 时崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:13 31 4
gpt4 key购买 nike

我不明白为什么下面这段代码会使我的程序崩溃。 'fp' 在执行 'fopen()' 后未被修改。

    FILE * fp;
char * line = NULL;
int len = 0;
int read;
char filePath[100] = "";

//Quick concatenate, I should use concatain but nah.
snprintf(filePath,sizeof(filePath), "%s/%s/%s",FOLDER_MAIN, "test", "data.txt");
fp = fopen(filePath, "r");
if (fp != NULL)
{
while ((read = getline(&line, &len, fp)) != -1)
{
if(startsWith(line, "value:"))
{
removeSubstring(line, "value:");
removeSubstring(line, " ");
removeSubstring(line, "\t");
removeSubstring(line, "\n");
printf("%d\t%s\n", 0, line);
}
}
fclose(fp);

//Free line pointer, is it really needed ?
if (line)
free(line);
}

int StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0)
return 1;

return 0;
}

void removeSubstring(char *s,const char *toremove)
{
while( s=strstr(s,toremove))
memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove)));
}

编辑:此外,'free(line)' 也会使程序崩溃。我添加了 removeSubstring 和 StartsWith 函数,希望对您有所帮助。无论如何,我认为这对程序影响不大,因为问题出在 fp 上......

最佳答案

您的代码是未定义的行为。

getline的原型(prototype)很清楚ssize_t getline(char **lineptr, size_t *n, FILE *stream);,使用时一定要特别使用正确的类型指针!

size_t len = 0;
ssize_t read;

编译器应该警告你。

关于调用 free() 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48163621/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com