簡體   English   中英

getline() memory 重新分配失敗

[英]getline() memory reallocation fails

使用FILE * some_file("somefile.txt", "r")成功打開文件后,我正在使用getline()讀取一行。 我可以提供getline()足夠的緩沖區char * line = malloc((size_t) 1024); ,效果很好。 我還可以提供比需要更少的緩沖區 - char * line = malloc((sizeof(char)))NULL -pointer char * line = NULL; ,並且,正如預期的那樣, getline()正在分配/重新分配和修改line的值。

char * line = malloc((sizeof(char)))
size_t n;
n = getline(&line, &n, some_file);

但是如果我聲明一個指針而不定義一些值或緩沖區,我會得到空間不足的錯誤(系統沒有崩潰。)。

char * line ;
size_t n;
n = getline(&line, &n, some_file); // Error: Not enough space

提供特定緩沖區char * line = malloc(sizeof(char)))之間的區別在哪里 - 它應該是指向 char 的指針(我知道我可以使用這個 memory 由於malloc() )和char * line; - 它也應該是一個指向 char 的指針(當然我不知道我是否可以使用這個 memory,但程序沒有崩潰)?

問題是缺少變量的初始化,這會導致getline不期望的值。 如果未初始化,則具有自動存儲持續時間的變量具有不確定的值 使用這些值將導致未定義的行為

初始化line的正確方法是將其設置為NULL並讓getline執行 malloc 似乎合適,

或者如果您已經分配了一些 memory 並且您堅持要在此處再次重用,則需要將n設置為 memory 分配的大小 即:

char * line = malloc(1);
size_t n = 1;
ssize_t rv = getline(&line, &n, some_file);

或者

char * line = NULL
size_t n; // or can explicitly initialize this to `= 0` but it shouldn't matter
ssize_t rv = getline(&line, &n, some_file);

因此,您問題中的兩個摘錄都是錯誤的。

最后,返回值是ssize_t類型,它n無關,除了返回時,它的值將嚴格小於存儲在n中的值。 您不能將其存儲在同一個變量中!


要使用getline處理某個文件中的每一行,無需調用malloc - 只需讓getline處理 memory 分配:

char * line = NULL;
size_t n = 0;
while (1) {
    errno = 0;
    ssize_t rv = getline(&line, &n, some_file);
    if (rv < 0) {
        if (feof(some_file)) {
            fprintf(stderr, "end of file, no problemo.");
        }
        else if (ferror(some_file)) {
            perror("an error occurred while reading from the file");
        }
        else {
            perror("some other error occurred");
        }
        free(line);
        break;
    }

    // at this point `line` points to an array
    // of `rv` characters, with possible embedded nulls,
    // meaning one line of data from the file,
    // + the terminating null character
    //
    // `n` is the *total number* of allocated bytes in the 
    // allocation pointed to by `line`.

    printf("I got a line of input: ");
    fwrite(line, 1, rv, stdout);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM