2016-11-23 30 views
-1

我試圖解析任意索引周圍的字符串。在我最簡單的測試程序中,我可以想出我有一個輸入字符串,我將輸入讀入,然後執行memcpy來解析字符串。將char *解析爲令牌時出現Segfault

爲了測試這個,我輸入「this text」作爲輸入。 readInput是一個函數,我只需要調用getline(&輸入,&大小,stinstin)並返回輸入指針。

int main(){ 
    char *input; 
    input = readInput(); 

    int parseAround = 4; 
    char *token1; 
    char *token2; 

    memcpy(token1, inputBuffer, 4); 
    printf("token: %s\n", token1); //prints "this" 

    memcpy(token1, inputBuffer + (parseAround+1), 4); 
    //when changed to memcpy(token2,...); segfaults 
    printf("token: %s\n", token1); //prints "text" 


    free(input); 
    return 0; 
} 

但是,當我更改第二個memcpy使用token2而不是令牌1時,出現分段錯誤。爲什麼是這樣?

+0

無論'token1'黑色'token2'初始化......它們指向隨機的地方。因此,當你對它們進行「memcpy」時,你正在複製到一個隨機位置,並且你錯誤地斷開了。 – NickStoughton

+0

'memcpy(token1,inputBuffer,4);'沒有分配給'token'的內存。 –

回答

1

您很可能需要爲token1分配內存。

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

int main(){ 
    char *input = NULL; 

    size_t len = 0; 
    ssize_t read; 

    /* Read in the line "Hello world" */ 
    read = getline(&input, &len, stdin); 
    printf("Retrieved line of length %zu :\n", read); 
    printf("%s", input); 

    /* Allocate memory for both parts of the string */ 
    char *token1 = malloc((read+1) * sizeof(char *)); 
    char *token2 = malloc((read+1) * sizeof(char *)); 

    memcpy(token1, input, 6); 
    printf("token: %s\n", token1); //prints "Hello" 

    memcpy(token2, (input+6), 5); 
    printf("token: %s\n", token2); //prints "world" 

    free(input); 
    return 0; 
} 

讀入行,每串部分分配內存,然後你想要的部分複製到你的S

+0

'getline'返回讀取的字符數,但不包括終止空字節('\ 0')。所以你應該在malloc()分配的空間中加一個來保存該字符串終止符。 – NickStoughton

+0

@NickStoughton編輯,謝謝。 – Chirality

相關問題