2014-02-12 49 views
0

具有以下結構和全局變量:分割故障多線程(ncurses的)

typedef struct Column{ 
    char * text; 
    int size; 
} Column; 

Column * screen; 

而這個線程函數:

void * thread_function(void * msg){ 
    Info *mesg = (Info *)msg; 
    int col = mesg->c; 

    int count = 0; 
    while (count < MAX_ELEM){ 
     if (rand() % 2){ 
      screen[col].text[count] = ' '; 
      screen[col].size++;  
      count++; 
     } 
     else{ 
      screen[col].text[count] = 'a'; 
      screen[col].size++;  
      count++; 
     } 
    } 
} 

在主函數中後,我加入了線程我開始打印內容screen

int row = 42; // num of rows on the screen 
while(true){ 
     int i; 
     for (i = 0; i<col; i++){ 
      int j = screen[i].size - 1; // print only up to already assign value 
      int k = 0; 
      while (j >= 0 && k < row){ 
       mvprintw(k,i,"%c",screen[i].text[j]); 
       refresh(); 
       j--; 
       k++; 
      } 
     } 
     refresh(); 
    } 

問題是一些運行正常執行,而其他人在while(true)的幾次迭代之後會產生Seg fault err錯誤(注意:至少總是打印一些東西)。如果我從while(true)中刪除mvprintw(),seg故障從不會發生。可能是什麼問題?

P.s.請不要發佈與互斥鎖有關的答案,因爲這是一項任務,我寧願糾正我遇到的問題,而是重新實現這個想法,尤其是當它可以在沒有互斥鎖的情況下執行時。

編輯:

分配全局變量screen(的主要部分)

screen = malloc(col * sizeof(Column *)); 
i = 0; 
    for (; i<col; i++){ 
     screen[i].text = malloc(MAX_ELEM * sizeof(char)); 
     screen[i].size = 0; 
    } 

輸出畫面在賽格故障:在沒有賽格故障

               a a    Segmentation fault (core dumped) 

輸出屏幕上:

  a       a a    a    a  aa 
         a a          a 
+0

u能PLZ發佈有關Screen'和'配置'一些代碼Screen-> text' –

+0

您是否嘗試過在調試器下運行您的代碼?另外,一個自包含的例子可能會幫助 – Hasturkun

+0

@Hasturkun我正在使用編輯器的代碼,手動調試,因爲它在問題中註明,'mvprintw()',因此'screen [i] .text [j] '會導致seg錯誤,儘管不應該像'screen [i]'存在並且'j'是大小,只有在實際將一個值分配給下一個時隙後,get纔會在main中增加。 –

回答

1

感覺到了

screen = malloc(col * sizeof(Column *));

screen = malloc(col * sizeof(Column)); 

因爲sizeof(Column *)將只返回指針的大小

+0

是的,這是問題,這是如此尷尬... –