未知段错误 - 带有简单的可重现示例

Unknown segfault - with simple reproduce-able example

我有这个简单的代码,它在 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;
}

如果删除 int *test[8] 行,它不会产生段错误。

它似乎不会在大多数 linux 系统上导致段错误,但它会在 ubuntu linux 子系统上为 windows gcc(或者可能是只是运气)?

我对 initstate_r 的使用实际上是错误的,我只是有时运气好?我看不出有什么问题吗?

谢谢!

来自the initstate_r manual page

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

您将指针传递给 未初始化 结构 rstate。这意味着该结构的所有成员都将未初始化并具有 indeterminate 值。如果 initstate_r 尝试访问这些成员,则可能会导致 未定义的行为

您至少需要将结构的 state 成员初始化为空指针:

rstate.state = NULL;