c - 在不同的位置打开文件会导致不同的结果

标签 c

test1.c:

int main(int argc, char *argv[])
    {
        FILE* fp = fopen("test.txt","rw");
        int n,m,q;
        scanf(" %d%d%d",&n,&m,&q);
        struct test_t test;
        while (fscanf(fp,"%d%s%d%d%d%d%d%d%d%*d",&test.line,test.data,&test.number[0],&test.number[1],&test.number[2],&test.number[3],&test.number[4],&test.number[5],&test.number[6])!=EOF) {
                //do something.....
        }
        return 0;
    }

test2.c:

int main(int argc, char *argv[])
{
    int n,m,q;
    scanf(" %d%d%d",&n,&m,&q);
    struct test_t test;
    FILE* fp = fopen("test.txt","rw");
    while (fscanf(fp,"%d%s%d%d%d%d%d%d%d%*d",&test.line,test.data,&test.number[0],&test.number[1],&test.number[2],&test.number[3],&test.number[4],&test.number[5],&test.number[6])!=EOF) {
            //do something....
    }
    return 0;
}

test_t的定义:

struct test_t {
    int line;
    char* data;
    int number[7];
};

我的测试.txt:

141 2015-12-05 19 16 35 06 34 46 09 00
124 2015-12-08 49 25 10 09 40 48 32 00
143 2015-12-10 09 29 24 47 32 34 42 00

当我使用 test1.c 时,出现段错误。但是当我使用 test2.c 时,它运行良好。只需更改 FILE* fp = fopen("test. txt","rw");。是什么导致了这种差异。

最佳答案

您正在调用 UB,因为您从未为 char* data; 分配内存。修复:

  1. mallocwhile 循环之前有足够的内存:

    test.data = malloc(32);
    if(!test.data)
    {
        fprintf(stderr, "malloc failed...Bailing out!\n");
        exit(-1);
    }
    

    使用后,

    free(test.data);
    
  2. 使用预定义大小的数组而不是指向 char 的指针:

    char data[32];
    
<小时/>

此外,如@AshishAhuja said ,还要检查fopen的返回值。

关于c - 在不同的位置打开文件会导致不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389625/

相关文章:

c - 我如何将其变成递减循环?

c - valgrind 条件跳转或移动取决于未初始化的值

iphone - 使用什么框架从 iPhone 连接到 SQL Server 实例?

c - 这些函数在将 kthreads 绑定(bind)到特定核心方面是否等效?

c - gluLookAt 不工作

c - 使用 ncurses 在 C 中显示 "int **array"

c - 处理内核模块上的 `Wframe-larger-than` 警告的建议

C编程数据输入错误

c - 避免逆矩阵

c - 由于字符串的格式以及所使用的参数,我的 printf 格式说明符将无法编译