Warm tip: This article is reproduced from serverfault.com, please click

C struct Segmentation fault

发布于 2020-11-30 14:39:15

After entering the second element, it throws me out x. I know that allocating memory for each element is not appropriate, but I wanted to better detect errors.I want to save two character fields for which I do not know the size in advance.

typedef struct
{
    char *m_Cislo;  
    char *m_Jmeno;
} TSEZNAM;

TSEZNAM * readNumbers (int *nr)
{   
    char *str = NULL;
    size_t  capacity = 0;

    TSEZNAM st;
    TSEZNAM *res = NULL;
    *nr=0;
    
    while ( getline(&str, &capacity, stdin) != -1 )
    {

        st.m_Jmeno = malloc(sizeof(char)*capacity);
        st.m_Cislo = malloc(sizeof(char)*capacity);
        
        sscanf(str,"%s %s", st.m_Cislo, st.m_Jmeno);

        TSEZNAM *tmp = (TSEZNAM*) malloc ((*nr+1)*sizeof(*res));

        for(int i=0; i < *nr; i++)
            tmp[i] = res[i];
            
        free(res);
        res=tmp;

        res[*nr]=st;
        *(nr)++;
        
    }
    
    return res;
}

int main(void)
{
    int listNr;
    TSEZNAM *list = readNumbers(&listNr);       
    
}
Questioner
Aaron7
Viewed
0
Adrian Mole 2020-11-30 22:57:17

The parentheses in your *(nr)++; statement actually achieve nothing (you are simply wrapping the name of the nr variable); thus, the effect of this statement is to increment the value of the pointer - which will cause problems in the second (and subsequent) loop(s), because it will then be pointing to an invalid location. This is because the post-increment (++) operator has higher precedence than the indirection (*) operator.

In fact, with full warnings enabled, your compiler will likely find this problem; for example, clang-cl gives:

warning : expression result unused [-Wunused-value]

To fix the problem, you need to place the dereference operator (*) inside the brackets, like this: (*nr)++.