2014-11-08 76 views
2

時我有一個程序運行的時候,送我一個分段違例顯然發生在函數「ejer6」試圖訪問的char * mensajeposition [0]當一個小問題來分配9我的代碼:段違規修改字符串

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

struct structure { 

    char * message; 
    int integer; 
}; 

void * ejer6(void * arg) { 

    printf("Enters within"); 

    struct structure * turas; 
    turas=((struct structure *)arg; 

    turas->integer=turas->integer+1; 
    turas->message[0]='9'; 

    printf("%d\n", turas->integer); 
    printf("%s\n", turas->message); 


    pthread_exit(NULL); 
} 

int main(int argc, char ** argv) { 
    if(argc!=2) { 
     printf("Enter the appropriate number of parameters\n"); 
    } 
    else { 

     pthread_t h[argc]; 
     struct structure turas[argc]; 
     int i; 

     for(i=0; i<argc; i++) { 
      turas[i].integer=13; 
      turas[i].message="hello world"; 
     } 

     for(i=0; i<argc; i++) { 

      printf("\nThis is the value of the structure before the strand: \n"); 
      printf("Integer: %d \n", turas[i].integer); 
      printf("Message: %s \n", turas[i].message); 


      pthread_create(&h[i], NULL, ejer6, (void *)&turas[i]); 
      pthread_join(h[i], NULL); 

      printf("\nThis is the value of the structure after the strand: \n"); 
      printf("Integer: %d \n", turas[i].integer); 
      printf("Message: %s \n", turas[i].message); 

     } 
    } 

    return 0; 
} 
+0

如果按順序執行它們,創建線程又有什麼意義? – 2014-11-08 12:33:33

+0

你可能想看看[這裏](http://meta.stackoverflow.com/questions/266563/do-non-english-words-increase-the-probability-of-receiving-downvotes/)瞭解如何非英文代碼會減少您獲得良好答案的機會。 – nvoigt 2014-11-08 12:37:37

回答

1

turas->mensaje指向您正試圖修改的字符串文字。在C中,這是未定義的行爲。使用數組或爲turas->mensaje分配內存並將字符串文字複製到其中。

您可以使用strdup()(POSIX函數)來分配內存:

turas[i].mensaje=strdup("Hola mundo"); 

,而不是

turas[i].mensaje="Hola mundo"; 

現在,你就可以修改它,你將不得不free內存由strdup()分配。

+2

和「malloc」會是:turas [i] .mensaje = malloc(argc * 12); – cheroky 2014-11-08 13:08:11

+0

不確定爲什麼包含一個因子'argc'。如果你喜歡使用'malloc()',爲字符串分配足夠的內存,並使用strcpy()'複製字符串:'turas [i] .mensaje = malloc(strlen(「Hola mundo」)+ 1); strcpy(turas [i] .mensaje,「Hola mundo」);'你還應該檢查'malloc()'是否失敗。 – 2014-11-08 13:13:34