Question

Having the following struct and global var:

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

Column * screen;

And this thread function:

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++;
        }
    }
}

In the main function after I join the threads I start printing the content of the 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();
    }

The issue is that some runs execute normally, while others generate a Seg fault err after a few iterations of the while(true)(Note: at least something is always printed). If I remove mvprintw() from the while(true) the seg fault never occurs. What can be the issue?

P.s. Please do not post answers which are related to mutex, as this is an assignment and I would prefer to correct the problem I have, rather reimplement the idea especially when it can be performed without mutex.

Edits:

allocation of global var screen (part of main)

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

Output screen at seg faults:

                                                              a a             Segmentation fault (core dumped)

Output screen at no seg fault:

         a                            a  a              a             a     aa
                        a  a                                        a
Was it helpful?

Solution

Feel that

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

to be

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

because sizeof(Column *) would return only the size of pointer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top