gpt4 book ai didi

c - fopen() 在 c 中第二次使用时崩溃

转载 作者:行者123 更新时间:2023-11-30 21:23:01 25 4
gpt4 key购买 nike

由于某种原因,fopens 在我的程序中不断崩溃。

当我读取输入文件并将内容放入变量中时,它会工作一次。但由于某种原因,当我尝试让它再次使用 fopens 时,它崩溃了......

有人可以帮忙吗

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *buf = "\0";
char buffer[99999] ;

int main(int argc, char *argv[])
{
ptr_file =fopen(inputFileLocation,"r");
if (!ptr_file)
{
return 1;
}
while (fgets(buf,maxvalue, ptr_file)!=NULL)
{
strcat(buffer,buf);
}
fclose(ptr_file);
... //workings
//then the program crashes if I add an fopen() and fclose() at the end

}

最佳答案

接受的答案没有捕获重点。这不仅仅是缓冲区溢出的问题。maxvalue = 2; 没有缓冲区溢出但程序会崩溃。

但是一步一步:

fgets(buf, maxvalue, ptr_file) != NULL

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first. A null character is automatically appended in str after the characters read to signal the end of the C string.

就您而言buf大小为 2 的字符串文字。这对于您的需求来说很可能太小了。但它不仅仅是 buf 的大小。 !

您无法将任何内容复制到(常量)字符串文字! 该操作会导致程序崩溃,信号为 11即使您读了一个字符。

常量是指程序在执行过程中不能改变的固定值。这些固定值也称为文字。

您需要的是char array尺寸合适。

您可以以与 char buffer[99999] 相同的方式声明它

// 1.
char buf[SIZE_OF_THE_BUF]; // remember that buf has to accept maxvalue-1 characters + `null` character

或者在 main() 中为其动态分配内存

//  2.a
char *buf;
//
int main()
{
// 2.b
buf = malloc(maxvalue * sizeof(char));
//...
}

关于c - fopen() 在 c 中第二次使用时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48967156/

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