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

fopen() crashing on second use in c

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

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

有人可以帮忙吗

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *buf = "[=10=]";
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

}

您创建了一个名为 buf 的指针,它指向 space,其中包含单个字符“\0”。 然后您使用 fgets() 尝试将未知数量的字符(您没有显示 maxvalue 是什么)读入 buf 指向的 space 中。但是 space 只有一个字符长。读取它会超出 space,导致未定义的行为。

接受的答案没有抓住重点。这不仅与缓冲区溢出有关。 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));
 //...
}