简体   繁体   English

使用fgets进行segfaulting,即使fopen在C中不返回NULL

[英]segfaulting with fgets, even though fopen doesn't return NULL in C

I've looked all over and made sure there were no warnings, but my code to replace text with digits keeps returning segfault. 我四处张望,确保没有任何警告,但是我用数字替换文本的代码不断返回段错误。 Any help? 有什么帮助吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc , char *argv[])
{
    FILE *file;
    file = fopen(argv[1] , "r");
    char *line = malloc(1024);
    if(file != NULL)
    {
        while(fgets(line , sizeof(line) , file))
        {
//things
        }
    }
    else
    {
        printf("ERROR: %s NOT AVAILABLE" , argv[1]);
    }
    return 0;
}

Replace: 更换:

char *line = malloc(1024);

with: 与:

char line[1024] = {0};

or: 要么:

char line[1024];

if you don't want to clear out the line buffer. 如果您不想清除行缓冲区。

Otherwise, you end up with two problems. 否则,您将面临两个问题。

First: 第一:

sizeof(line)

returns the size of the pointer (4 or 8 bytes). 返回指针的大小(4或8个字节)。 That's not what you want. 那不是你想要的。

Second: You have a memory leak because you don't free the line pointer at the end. 第二:内存泄漏,因为最后没有free line指针。

You can use malloc if you want, but you want to write clean(er) code to do this. 您可以根据需要使用malloc ,但是要编写干净的代码来执行此操作。 You might do something like: 您可能会执行以下操作:

#define MAX_LINE_LENGTH 1024

/* ... */

char *line = NULL;
line = malloc(MAX_LINE_LENGTH);
if (!line) {
    fprintf(stderr, "Error: Could not allocate space for line buffer!\n");
    exit(EXIT_FAILURE);
}

FILE *file = NULL;

/* Avoid undefined behavior by making sure filename argument holds a value */

if (argv[1])
    file = fopen(argv[1] , "r");

if (file != NULL) { /* You could also do "if (file) { ... }" */
    while (fgets(line, MAX_LINE_LENGTH, file)) {
        /* ... */
    }
}

free(line);
line = NULL;

As a habit, explicitly initialize pointers to NULL , and check that they actually hold a value before using them. 作为一种习惯,请显式地初始化指向NULL指针,并在使用它们之前检查它们是否真正拥有一个值。 Welcome to C! 欢迎来到C!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM