Search code examples
cpointersmemset

Program crash on memset?


I am struggling with memset.

If I write in my array my program crashes. If I comment out the memset i have no problems.

My type struct:

typedef struct  
{
    char Frage  [maxLEN_F_A];
    char Antwort[maxLEN_F_A];
} Fragenfeld;

My declaration of the struct:

Fragenfeld QuizFragen[maxFragen];
Fragenfeld *ptrQuizFragen = QuizFragen;

The memset call:

memset(&ptrQuizFragen,0,maxFragen*sizeof(Fragenfeld));

My function, where I edit the value of the adress:

int Fragen_einlesen(Fragenfeld *Quizfragen)
{
....
strncpy(Quizfragen->Frage,sEingabe, maxLEN_F_A);
}

Solution

  • When you write

    memset(&ptrQuizFragen,0,maxFragen*sizeof(Fragenfeld));
    

    you're saying "please set a lot of of bytes, starting at the address of the pointer variable ptrQuizFragen, to zero." Notice that this is different than saying "please set a lot of bytes, starting at the beginning of the array pointed at by ptrQuizFragen, to zero." This means the bytes are getting written to the wrong place, which is what's causing your segfault.

    Graphically, the setup looks something like this:

    ptrQuizFragen
    +-----------+
    |           |
    +-----------+
          |
          v
    +-----------+-----------+-----------+ ... +-----------+
    |           |           |           |     |           |
    +-----------+-----------+-----------+ ... +-----------+
    QuizFragen
    

    The line you've written puts the bytes starting where ptrQuizFragen is located in memory, which does this:

    ptrQuizFragen
    +-----------+
    | 00000000000000000000000000000000000 ... 000000000000 (oops!)
    +-----------+
           
           
    +-----------+-----------+-----------+ ... +-----------+
    |           |           |           |     |           |
    +-----------+-----------+-----------+ ... +-----------+
    QuizFragen
    

    The line you want is

    memset(ptrQuizFragen, 0, maxFragen * sizeof(Fragenfeld));
    

    which says to put the bytes at the memory location pointed at by ptrQuizFragen. That would do this:

    ptrQuizFragen
    +-----------+
    |           |
    +-----------+
          |
          v
    +-----------+-----------+-----------+ ... +-----------+
    | 000000000 | 000000000 | 000000000 |     | 000000000 |
    +-----------+-----------+-----------+ ... +-----------+
    QuizFragen