1

tmp の内容を tmp2 に保存する必要があります。ただし、while ループの外では、tmp は常に NULL です。

if(1){

        char* tmp;
        char* tmp2;

        // split the string on the space character
        tmp = strtok(actual_args[0], " ");

        while(tmp != NULL){
            strcpy(tmp2, tmp);
            tmp = strtok(NULL, " ");                
        }


        // always NULL
        printf("%s", tmp);

        // produces seg. fault
        printf("%s", tmp2);



}
4

3 に答える 3

0

コードの問題は、strcpy正しく使用されていないことです。関数は文字列の内容をコピーしますが、文字列のメモリのコピーを作成しません。

目的の文字列にメモリを割り当てるのはあなたの仕事です。自動メモリ (つまり、スタック)、静的メモリ、または動的メモリ (つまり、ヒープ) で実行できます。

文字列に動的メモリを割り当てたい場合は、次のようにできます。

char tmp2 = NULL; // Don't forget to initialize tmp2
...
while(tmp != NULL){
    free(tmp2);                   // Free the old content of tmp2
    tmp2 = malloc(strlen(tmp)+1); // Add one byte for null terminator
    strcpy(tmp2, tmp);            // Now the copy has space to which the data is copied
    tmp = strtok(NULL, " ");                
}
... // Use tmp2 ...
free(tmp2); // You need to free dynamically allocated memory

これにも非標準strdup関数を使用できますが、お勧めしません。

于 2014-04-22T02:12:49.043 に答える