【发布时间】:2014-05-01 06:00:25
【问题描述】:
所以我有一个测试程序,它将大量数据读入缓冲区并分配 相应地缓冲。但是它 malloc 在大尺寸上失败了。
有没有办法解决这个问题?
感谢任何回复
设备 /dev/sdc 是 2TB 磁盘。
这里准备好2个编译代码:
#define _FILE_OFFSET_BITS 64
#define BLKGETSIZE64 _IOR(0x12,114,size_t)
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int readdata(int fp,uint64_t seekpoint, uint64_t seekwidth) {
int16_t *buf;
buf=(int16_t *)malloc(seekwidth*sizeof(int16_t)+1);
if (buf==0) {
printf("ERROR malloc(%"PRIu64")\n",seekwidth*(sizeof(int16_t)));
return 3;
}
if (pread(fp,buf,seekwidth,seekpoint)==seekwidth) {
printf("SUCCES READING AT: %"PRIu64"| WITH READ WIDTH: %"PRIu64"\n",seekpoint,seekwidth);
free(buf);
return 1;
} else {
printf("ERROR READING AT: %"PRIu64"| WITH READ WIDTH: %"PRIu64"\n",seekpoint,seekwidth);
free(buf);
return 2;
}
}
int main() {
uint64_t readwith,
offset;
int fp=open("/dev/sdc",O_RDWR);
readwith=10000; offset=0;
readdata(fp,offset,readwith);
readwith=100000; offset=0;
readdata(fp,offset,readwith);
readwith=1000000; offset=0;
readdata(fp,offset,readwith);
readwith=10000000; offset=0;
readdata(fp,offset,readwith);
readwith=100000000; offset=0;
readdata(fp,offset,readwith);
readwith=1000000000; offset=0;
readdata(fp,offset,readwith);
readwith=10000000000; offset=0;
readdata(fp,offset,readwith);
close(fp);
}
我系统上的输出是:
SUCCES READING AT: 0| WITH READ WIDTH: 10000
SUCCES READING AT: 0| WITH READ WIDTH: 100000
SUCCES READING AT: 0| WITH READ WIDTH: 1000000
SUCCES READING AT: 0| WITH READ WIDTH: 10000000
SUCCES READING AT: 0| WITH READ WIDTH: 100000000
SUCCES READING AT: 0| WITH READ WIDTH: 1000000000
ERROR READING AT: 0| WITH READ WIDTH: 10000000000
ERROR READING AT: 0| WITH READ WIDTH: 100000000000
ERROR READING AT: 0| WITH READ WIDTH: 1000000000000
ERROR READING AT: 0| WITH READ WIDTH: 10000000000000
ERROR READING AT: 0| WITH READ WIDTH: 100000000000000
ERROR READING AT: 0| WITH READ WIDTH: 1000000000000000
有时
ERROR malloc(2000000000)
ERROR READING AT: 0| WITH READ WIDTH: 10000000000
【问题讨论】:
-
既然这是/dev/sdc,我猜它是一个闪存驱动器?也许您正在尝试分配比它更多的内存?另外,它在哪一边失败了?
-
这是一个 2TB 磁盘,我在我的系统上添加了输出
-
您应该在
malloc或pread等失败时打印strerror(errno)...
标签: c linux memory-management malloc