繁体   English   中英

将文件读入缓冲区,但调用fseek后程序在fread时崩溃

[英]read a file into a buffer, but program crashes at fread after calling fseek

我想将文件读入缓冲区。 我在fread()遇到分段错误。 看起来ftell()给出了正确的大小。 但是后来出了问题。 fseek()修改f吗? 为什么fread()不起作用?

int pk_load_file( const char *filename )
{
    FILE *f;
    int size;
    unsigned char *buf;

    if( ( f = fopen( filename, "rb" ) ) == NULL )
        return -1;

    fseek( f, 0, SEEK_END );

    if( ( size = ftell( f ) ) == -1 )
    {
        fclose( f );
        return -2;
    }

    fseek( f, 0, SEEK_SET );

    if( fread( buf, 1, size, f ) != size )
    {
        fclose( f );
        return -3;
    }

    fclose( f );

    return( 0 );
 }

这里的问题是

if( fread( buf, 1, size, f ) != size )

在上述情况下,您使用的buf未初始化。 您需要在使用前为buf分配内存。

未初始化时, buf可以指向该进程无法访问的任何内存位置。 因此,尝试访问buf的内存会调用未定义的行为

分割错误是副作用之一。

解决方案:您可以使用malloc()和family将内存分配给buf

正确的代码:

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

int pk_load_file( const char *filename ) {
    FILE *f;
    int size;
    unsigned char *buf;

    if ((f = fopen(filename, "rb")) == NULL) {
        return -1;
    }

    fseek(f, 0, SEEK_END);

    if ((size = ftell(f)) == -1) {
        fclose(f);
        return -2;
    }

    buf = malloc(size); // here is the magic. you need to allocate "size" bytes

    if (buf == NULL) {
        fclose(f);
        return -3;
    }

    fseek(f, 0, SEEK_SET);

    if (fread(buf, 1, size, f) != size) {
        fclose(f);
        return -4;
    }

    fclose(f);

    return 0;
}
 unsigned char *buf;

如上所述,答案给出了未定义的行为,因此可以使用动态分配或将其声明为数组,

 #define  MAX_LENGTH 1024
 unsigned char buf[MAX_LENGTH];

并将其传递给fread()

暂无
暂无

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

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