【问题标题】:Segmentation fault with multithreading (ncurses)多线程的分段错误(ncurses)
【发布时间】:2014-02-12 19:32:45
【问题描述】:

具有以下结构和全局变量:

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 错误错误(注意:至少总是打印一些内容)。如果我从while(true) 中删除mvprintw(),则永远不会发生段错误。可能是什么问题?

附:请不要发布与互斥锁相关的答案,因为这是一项作业,我更愿意纠正我遇到的问题,而是重新实现这个想法,特别是当它可以在没有互斥锁的情况下执行时。

编辑:

分配全局变量screen(main的一部分)

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

【问题讨论】:

  • 能否请您发布一些有关ScreenScreen-&gt;text 分配的代码
  • 你试过在调试器下运行你的代码吗?另外,一个独立的例子可能会有所帮助
  • @Hasturkun 我正在使用代码编辑器,手动调试,正如问题中所述,mvprintw() 和因此screen[i].text[j] 导致 seg 错误,虽然不应该像 @ 987654336@ 存在,j 是大小,只有在将值实际分配给下一个插槽后,它才会在 main 中递增。
  • 愚蠢的问题,但是你有没有机会在同一个screen[col] 上运行你的线程两次?这将使screen[col].size &gt; MAX_ELEM。我只提到这一点是因为您的线程函数使用两个计数器,countsize。在这种情况下,只有其中一个会归零。

标签: c multithreading ncurses


【解决方案1】:

感觉

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

成为

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

因为sizeof(Column *) 只会返回指针的大小

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2015-06-09
    • 2016-02-09
    • 2011-03-17
    相关资源
    最近更新 更多