0

我使用 realloc 动态增加 char 指针 (*seqA) 的大小。还有其他更好的方法吗?

这是我的代码的一部分:

    while((holder=fgetc(fileA)) != EOF) {
    lenA++;
    temp=(char*)realloc(seqA,lenA*sizeof(char));
    if (temp!=NULL) {
        seqA=temp;
    seqA[lenA-1]=holder;
    }
    else {
        free (seqA);
        puts ("Error (re)allocating memory");
        exit (1);
    }
}
4

2 回答 2

1

由于您的代码正在将完整文件读入字符串,为什么不使用以下代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

....

struct stat buf;
fstat(fileno(fileA), &buf);
seqA = malloc(buf.st_size);
fread(seqA, buf.st_size, 1, fileA);

当然,您应该检查这些函数的返回值并采取适当的措施。

于 2013-03-04T12:15:44.623 回答
0

为什么要质疑算法的一小部分?更全面地审视整个算法可能是一个更好的主意。您当前的算法依赖于这种相当密集且不必要的代码。如果您可以消除将整个文件读入内存的依赖,那么您的解决方案将更具可扩展性。也许通过“一种更好的方法”,您的意思是“更快”或“这样我就可以处理 100GB 大小的文件而不会停止爬行”。

Consider a finite state machine that can read, process and extract the required information from your file one byte at a time. You probably wouldn't need malloc so much. Without a specific description of your problem, we can't help you derive a finite state machine to solve your problem. However, one example that stands out might be finding a maximum integer in a 100GB file:

while (fscanf(file, "%d", &current_num) == 1) {
    if (current_num > max_num) {
        max_num = current_num;
    }
}

This code clearly doesn't need malloc, let alone to read the entire file into memory; It'll only ever use a constant amount of memory, regardless of the size of the file.

于 2013-03-04T14:42:26.517 回答