glibc rand() 不适用于 python 但在在线编译器中运行良好

glibc rand() doesn't work with python but works fine in online compiler

我正在尝试将 glibc rand() 函数嵌入 python。我的目的是根据使用 LCG 的假设来预测 rand() 的下一个值。我读到它只有在 8 字节状态下运行时才使用 LCG,所以我正在尝试使用 initstate 方法来设置它。

我的 glibc_random.c 文件中有以下代码:

#include <stdlib.h>
#include "glibc_random.h"

void initialize()
{
    unsigned int seed = 1;
    char state[8];

    initstate(seed, state, sizeof(state));
}

long int call_glibc_random()
{
    long r = rand();
    return r;
}

和下面各自的glibc_random.h

void initialize();
long int call_glibc_random();

python中的代码:

def test():
    glibc_random.initialize()
    number_of_initial_values = 10
    number_of_values_to_predict = 5
    initial_values = []

    for i in range(number_of_initial_values):
        initial_values.extend([glibc_random.call_glibc_random()])

在 python 中调用时,上面的代码不断将 12345 添加到我的 initial_values 列表中。但是,当 运行 www.onlinegdb.com 中的 C 代码时,我得到了一个更合理的数字列表(11035275900、3774015750 等)。当我在 initialize() 方法中调用 initstate(seed, state, sizeof(state)) 后使用 setstate(state) 时,我只能在 onlinegdb 中重现我的问题。

任何人都可以指出这里有什么问题吗?我正在使用 swig 和 python2.7,顺便说一句。

我以前从未使用过initstate但是

void initialize()
{
    unsigned int seed = 1;
    char state[8];

    initstate(seed, state, sizeof(state));
}

我觉得不对。 stateinitialize 的局部变量,当 函数结束,变量停止退出,所以 rand() 可能会给你垃圾 因为它试图访问一个不再有效的指针。

您可以将 state 声明为 static,这样它就不会消失 initialize结束,

void initialize()
{
    unsigned int seed = 1;
    static char state[8];

    initstate(seed, state, sizeof(state));
}

或使state成为全局变量。

char state[8];

void initialize()
{
    unsigned int seed = 1;

    initstate(seed, state, sizeof(state));
}