在fread和fwrite中,即使我使用了malloc,C也出现了分割错误 [英] Segmentation fault in C with fread and fwrite even though I used malloc

查看:159
本文介绍了在fread和fwrite中,即使我使用了malloc,C也出现了分割错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究一个由于分段错误而不断崩溃的程序。我把代码中最简单的部分引起了这个问题。
据我所知,到目前为止,如果我要求操作系统进行内存分配,然后使用指针读取和写入内存的地址,应该是好的。



在这种情况下,下面的剪切看起来很简单:打开一个新文件来写入,打开源文件,创建 outdata 来保存足够的字节,从源读取字节的确切值,并用 fwrite 用相同的参数写入新文件。



有没有什么基本的东西我在这里失踪?

pre $

文件* outimg = fopen(test.jpg,w);
FILE * rawFile = fopen(source.file,r);
if(rawFile == NULL)
{
fprintf(stderr,Unable to open source file\\\
);
返回1;
}
int chunkSize = 512;
int picChunkCount = 440;
unsigned char * outdata = malloc(chunkSize * picChunkCount * sizeof(unsigned char));
if(outdata == NULL)
{
fprintf(stderr,Unable to allocate memory for * outdata \\\
);
返回2;

fread(& outdata,sizeof(unsigned char)* chunkSize * picChunkCount,1,rawFile);
fwrite(& outdata,sizeof(unsigned char)* chunkSize * picChunkCount,1,outimg);



$ b $ div class =h2_lin>解决方案

fread fwrite



这是因为 outdata 已经指向位置,由 malloc()



PS不要忘了 free(outdata);


I have been working on a program that keeps crashing due to segmentation fault. I cropped out the simplest part of the code causing this issue. According to what I learnt so far, if I ask the OS for memory allocation, and then use the pointer to read&write to that address of the memory, it should be good to go.

In this case, the following snipped looks pretty simple to me: opening a new file for writing, opening source file, creating outdata to hold enough bytes, reading the exact value of bytes from source and writing to new file with fwrite with same parameters.

Is there something fundamental I'm missing here?

int main (void)
{
    FILE *outimg = fopen("test.jpg", "w");
    FILE *rawFile = fopen("source.file", "r");
    if(rawFile==NULL)
    {
      fprintf(stderr, "Unable to open source file\n");
      return 1;
    }
    int chunkSize = 512;
    int picChunkCount = 440;
    unsigned char *outdata = malloc(chunkSize*picChunkCount*sizeof(unsigned char));
    if(outdata==NULL)
    {
      fprintf(stderr,"Unable to allocate memory for *outdata\n");
      return 2;
    }
    fread(&outdata, sizeof(unsigned char)*chunkSize*picChunkCount,1, rawFile);
    fwrite(&outdata, sizeof(unsigned char)*chunkSize*picChunkCount, 1, outimg);
}

解决方案

Just remove & in fread and fwrite.

That's because outdata already points to location, allocated by malloc().

P.S. Don't forget to free(outdata);

这篇关于在fread和fwrite中,即使我使用了malloc,C也出现了分割错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆