我的 fread 程序出了什么问题?
我正在从二进制文件中读取内容。如果我以 char 形式读入数据元素,则不会收到任何 malloc 错误,但如果我以任何其他数据类型(例如短整型或 int)读入,程序会成功读入字节,但是当我 free 我得到的指针这可能是由于堆损坏造成的。有人能告诉我我做错了什么吗?
代码:
#include <stdio.h>
#include <stdlib.h>
#define TYPE int //char or short
int main () {
FILE * pFile;
long lSize;
TYPE * buffer;
size_t result;
pFile = fopen ( "4.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (TYPE*) malloc (lSize/sizeof(TYPE));
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,sizeof(TYPE),lSize/sizeof(TYPE),pFile);
if (result != lSize/sizeof(TYPE)) {fputs ("Reading error",stderr); exit (3);}
perror("This is the problem: ");
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
free (buffer); // free causes heap related issue
return 0;
}
I'm reading contents from a binary file. If I read in data elements as char I don't get any malloc errors, but if I read in as any other data types, say short or int, the program successfully reads in the bytes but when I free the pointer I get This may be due to a corruption of the heap. Can someone tell me what wrong I'm doing?
The code:
#include <stdio.h>
#include <stdlib.h>
#define TYPE int //char or short
int main () {
FILE * pFile;
long lSize;
TYPE * buffer;
size_t result;
pFile = fopen ( "4.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (TYPE*) malloc (lSize/sizeof(TYPE));
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,sizeof(TYPE),lSize/sizeof(TYPE),pFile);
if (result != lSize/sizeof(TYPE)) {fputs ("Reading error",stderr); exit (3);}
perror("This is the problem: ");
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
free (buffer); // free causes heap related issue
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
malloc
将大小(以字节为单位)作为参数,因此该行应为
malloc
takes a size in bytes as a parameter, so the lineshould read