0

以下代码加载到一个名为 gasses.txt 的文本文件中,该文件有 16 个术语,每个术语占一行,并将这些术语一次存储在缓冲区 search_terms 中。

#define MAX_LINE_LEN 40
FILE *dict_fp;
int term_len;
int j;

size_t number_search_terms = 10;
int i;
char **search_terms = malloc(sizeof(char *) * number_search_terms);
for (i=0; i < number_search_terms; i++)
    search_terms[i] = malloc(MAX_LINE_LEN);

dict_fp = fopen("gasses.txt", "r");
for (i=0; fgets(search_terms[i], MAX_LINE_LEN, dict_fp) != NULL; i++){

    // get rid of the newline.
    term_len = strlen(search_terms[i]);
    search_terms[i][term_len-1] = 0;

    // resize buffer when it gets full
    if (i == number_search_terms-1){
        number_search_terms *= 2;
        search_terms = realloc(search_terms, number_search_terms);      
        for (j = number_search_terms/2; j < number_search_terms; j++)
            search_terms[j] = malloc(MAX_LINE_LEN);
    }

    printf("%s\n", search_terms[i]);

    printf("%s\n\n", search_terms[0]);

}

输出看起来像这样。在第一次内存重新分配后,存储在 search_terms[0] 中的字符串被损坏。

nitrogen
nitrogen

oxygen
nitrogen

argon
nitrogen

carbon dioxide
nitrogen

neon
nitrogen

helium
nitrogen

methane
nitrogen

krypton
nitrogen

hydogen
nitrogen

nitrous oxide
���

xenon
���

ozone
���

nitrogen dioxide
���

iodine
���

ammonia
���

water vapour
���

这是gasses.txt:

oxygen
argon
carbon dioxide
neon
helium
methane
krypton
hydogen
nitrous oxide
xenon
ozone
nitrogen dioxide
iodine
ammonia
water vapour
4

1 回答 1

3

当您第一次 malloc 为 search_terms 时,您正确地使用sizeof(char *) * number_search_terms了大小。

但是,当您重新分配时,您会使用它number_search_terms。这个新大小是正确大小的 1/4 或 1/8(取决于您的指针大小),因此您最终会写入超过此缓冲区的末尾。

于 2013-10-31T20:28:06.567 回答