2016-10-18 27 views
1

我正在做一個創建一個漫遊互聯網的機器人項目。printf只顯示字符的24個字符*

我必須用C語言編寫代碼,現在我正在關注它將要去的地址的選擇(從文件列表中選擇)。這工作正常,但是當我顯示機器人選擇的地址時,有些被截斷爲24個字符並以「!」結尾這使得代碼不能用於長地址。有沒有人知道它會來的地方?

程序:

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <string.h> 
#include <math.h> 

int main() { 
    FILE* file = fopen("test.txt", "r+"); 

    char *line = NULL; 
    char *tab[1023]; 
    int tailleTab = 0; 

    line = malloc(sizeof(*line)); 

    if(line == NULL) 
    return(EXIT_FAILURE); 

    while((fgets(line, 1023, file)) != NULL) { 
    if(line[0] != '#' && line[0] != '\n') { 
     tab[tailleTab] = line; 
     line = malloc(sizeof(*line)); 
     tailleTab++; 
    } 
    } 

    srand(time(NULL)); 
    int n = rand()%tailleTab; 
    printf("\n%d = %.32s\n", n, tab[n]); 
    printf("%s\n", tab[n]); 
    fclose(file); 
} 

從中選擇的地址的文件:

www.google.com 
www.wikipedia.org 
www.dahunicorn.xyz 
www.cloudimperiumgames.com 
www.robertspaceindustries.com 
www.candybox2.net 
www.42.com 
www.1337.com 
+0

請分享您的輸入 - 我們無法猜測它!另外,請分享您的調試觀察。 –

+0

請在使用後免費分配。好的習慣也可以在簡單的測試片段中做到這一點。 – maxik

回答

1

的主要問題是這樣的:

line = malloc(sizeof(*line)); 

這僅分配一個單個字符到line。表達式*line是一個char,這意味着您分配sizeof(char)字節,並且sizeof(char)被定義爲始終爲1

這意味着您致電fgets將寫出您分配的內存的界限,並且您將有未定義的行爲

沒有理由動態地分配line。請將其創建爲數組,然後在將其保存在tab陣列中時使用strdup。要麼或分配更多的內存(1023是一個很好的數字,因爲這是你傳遞給fgets)。

0

如已經在另一個答案所解釋的,與此代碼:

line = malloc(sizeof(*line)); 

你與malloc在堆中的單個char分配,因爲表達式*line相當於char(如line宣佈爲char *)。

我會使用命名常量,而不是神奇數字1023是通過代碼傳播簡化代碼(並使其更難維護),除了剛纔預留空間棧上的臨時line緩衝液代替動態分配它在堆上,例如:

/* Instead of: line = malloc(sizeof(*line)); */ 
#define LINE_MAX_SIZE 1024 
char line[LINE_MAX_SIZE]; 

也可以考慮這樣做:

#define TAB_MAX_ITEMS /* 1023 or whatever */ 
char* tab[TAB_MAX_ITEMS]; 

while循環考慮使用LINE_MAX_SIZE而不是幻數1023的:

while ((fgets(line, LINE_MAX_SIZE, file)) != NULL) { 

您可能還需要檢查添加到索引在tab陣列中,以避免緩衝區溢出:

if (tailleTab >= TAB_MAX_ITEMS) { 
    /* Index out of range */ 
    ... 
} 

/* tailleTab is a valid index. 
* Deep-copy the line read in the temporary buffer 
* and save a pointer to the copy into the tab array. 
*/ 
tab[tailleTab] = strdup(line); 

在生產代碼中,您還應該遍歷存儲在tab數組中的指針,並在其上調用free以釋放堆中分配的內存。