【发布时间】:2016-07-19 14:23:36
【问题描述】:
我需要从一个文件中读取 4,000,000,000 行并将它们保存到一个数组中。
但是Linux内核因为内存不足而杀死了进程:
tail /var/log/kern.log
... Out of memory: Kill process ...
代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
/*
* Read line by line from the file and write into the array
*/
int lines_allocated = 128;
int max_line_len = 15;
char **array = (char **)malloc(sizeof(char*)*lines_allocated);
if (array==NULL) {
fprintf(stderr,"Out of memory (1).\n");
exit(1);
}
file = fopen("file", "r");
if (file == NULL) {
fprintf(stderr,"Error opening file.\n");
exit(2);
}
int il;
for (il=0;1;il++) {
int j;
/* Have we gone over our line allocation? */
if (il >= lines_allocated) {
int new_size;
/* Double our allocation and re-allocate */
new_size = lines_allocated*2;
array = (char **)realloc(array,sizeof(char*)*new_size);
if (array==NULL){
fprintf(stderr,"Out of memory.\n");
exit(3);
}
lines_allocated = new_size;
}
/* Allocate space for the next line */
array[il] = malloc(max_line_len);
if (array[il]==NULL)
{
fprintf(stderr,"Out of memory (3).\n");
exit(4);
}
if (fgets(array[il], max_line_len-1, file)==NULL)
break;
/* Get rid of CR or LF at end of line */
for (j=strlen(array[il])-1;j>=0 && (array[il][j]=='\n' || array[il][j]=='\r');j--)
;
array[il][j+1]='\0';
}
/* Close login file */
fclose(file);
/* Print the array of data from the file */
for (i=0; i < il; i++)
printf("%s\n", array[i]);
return 0;
}
什么是最合适和最有效的方法?也许读取第一个块,完成它,然后读取下一个块等等?
这个问题有什么解决办法?
【问题讨论】:
-
在较小的行之后阅读它。
-
如您所说,您可以一次读取 1 行,对其进行处理,然后对剩余的数据行执行相同操作。
-
你自己回答了。一块一块是正确的方法
-
您需要同时处理所有的数据吗?还是顺序?如果您可以按顺序处理它,那么一次读取并处理一行。否则分块读取。或者你可以memory map the whole or part of the file。
-
“最合适的方式”取决于您将如何处理这些数据。给我们更多的背景信息。
标签: c linux memory-management out-of-memory