2012-04-24 34 views
1

處理一個問題,即必須從文件讀取數據到結構中。嘗試爲結構中的字符串分配內存時出現分段錯誤

該文件的組織方式使得有一個名字,幾行ASCII藝術以#和評分結尾。下面是一個例子

Sample Name 
(S) 
(S) 
# 5 

我有我的結構設置是這樣的:

typedef struct 
{ 
    char* name; 
    char* art; 
    int rating; 
}CASE; 

我的問題是,我不斷收到一個segmentation fault當我試圖動態分配內存的代碼名稱的字符串如下:

/*FPin is file pointer to the txt file and all is the array of structs*/ 
void readFile(FILE* FPin, CASE** all) 
{ 
    CASE* walker = *all; 
    int count = 0; 
    char buffer[160]; 
    char* bufferPtr = buffer; 
    char nameBuffer[100]; 

    /*Reads in the name*/ 

    while(fscanf(FPin, "%[^\n]", nameBuffer)) 
    { 
    printf("string is %s\n", nameBuffer); 
    walker->name = (char*)malloc(sizeof(char)*(strlen(nameBuffer+1))); /*ERROR*/ 
    strcpy(walker->name, nameBuffer); 
    } 

    return; 
    } 

我做了一個記下我認爲錯誤是上面,因爲代碼,一旦我說那行,我開始了。

我基本上是從文本讀取一個名稱到一個nameBuffer(數組),然後使用strcpy將該名稱複製到結構中。有關如何解決這個問題的任何建議?

感謝您的期待。

我將列舉以下我的源代碼的其餘部分:

int main (void) 
{ 
    CASE* all; 
    FILE* FPin; 

    if((FPin = fopen("art.txt", "r")) == NULL) 
    { 
    printf("Error opening file."); 
    exit(100); 
    } 

    allocateStructMem(&all); 
    readFile(FPin, &all); 

    fclose(FPin); 
    return 0; 
} 

void allocateStructMem (CASE** all) 
{ 
    if((*all = (CASE*)malloc(sizeof(CASE)*1000)) == NULL) 
    { 
     printf("Fatal memory error!\n"); 
     exit(1); 
    } 

    return; 
} 

回答

3

的strlen(nameBuffer + 1)

strlen(nameBuffer)+1 

你也必須做這樣的事情,當你的malloc all

int allocateStructMem(CASE **all) 
{ 
    /* +----- Note. And no need to cast as malloc returns (void *) 
     |           */ 
    if((*all = malloc(sizeof(CASE*) * 1000)) == NULL) 

爲了防止溢出,你必須限制長度爲fscanf,即:

while (fscanf(FPin, "%99[^\n]", nameBuffer) == 1) { 

1確保您已經實際讀取了一些名稱爲nameBuffer的內容。

strcpy不墊 - 但你可能知道。

2

是否移動+1括號外幫助嗎?

walker->name = (char*)malloc(sizeof(char)*(strlen(nameBuffer)+1)); /*ERROR*/