Search code examples
csegmentation-faultglibcwindows-subsystem-for-linux

Unknown segfault - with simple reproduce-able example


I have this simple code which causes a segfault in initstate_r:

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char *argv[])
{
    int *test[8];

    struct random_data rstate;
    char random_bin[256];
    initstate_r(1,random_bin,256,&rstate);

    test[0] = NULL;

    printf("%p",test[0]);

    return 0;
}

It does not produce a segfault if int *test[8] lines are removed.

It doesn't seem to cause a segfault on most linux systems, but it does on ubuntu linux subsystem for windows gcc (or maybe that is just luck)?

Is my use of initstate_r actually wrong and I just get lucky sometimes? I don't see anything wrong with it?

Thanks!


Solution

  • From the initstate_r manual page:

    Before calling this function, the buf.state field must be initialized to NULL.

    You pass a pointer to the uninitialized structure rstate. That means all members of the structure will be uninitialized and have indeterminate values. If the initstate_r attempt to access these members then it could lead to undefined behavior.

    You need to initialize at least the state member of the structure to a null pointer:

    rstate.state = NULL;