【问题标题】:C: initstate_r crashingC: initstate_r 崩溃
【发布时间】:2010-11-12 16:51:26
【问题描述】:

我在尝试使用 initstate_r 时遇到了崩溃:

(gdb) run
Starting program: /home/user/test.out

Program received signal SIGSEGV, Segmentation fault.
0x40052d00 in initstate_r () from /lib/libc.so.6

代码:

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

#define STATELEN    256             /* random number state buffer */

main()
{
 char randomStateBuffer[STATELEN];
 struct random_data randData;

 printf("Before initstate");
   /* seed the random number generator */
    initstate_r (time(NULL), (char *)&randomStateBuffer, STATELEN,
   (struct random_data *)&randData);
 printf("initstate done");

}

我已经尝试在 gcc 3.3.6 和 4.3.3 中编译它并且都发生了崩溃。

【问题讨论】:

    标签: c random crash segmentation-fault


    【解决方案1】:

    在调用 initstate_r() 之前尝试将 randData 结构清零。
    memset( &amp;randData, 0, sizeof( random_data ) );
    (从这个页面得到提示:http://sourceware.org/bugzilla/show_bug.cgi?id=3662

    【讨论】:

    • memset( &randData, 0, sizeof( struct random_data ) );仍然崩溃。 (gdb) 运行启动程序:/home/zeno/test433.out 程序收到信号 SIGSEGV,分段错误。 0x40052c33 initstate_r () from /lib/libc.so.6
    • 这对我来说是个问题,但请注意,您需要将此与 Joe Valenzuela 关于将 adddress-of 运算符放在 randomStateBuffer 上的说明结合起来。
    【解决方案2】:

    查看函数签名,第二个参数只是一个 char*。从 randomStateBuffer 中取出操作符的地址。

    initstate_r (time(NULL), randomStateBuffer, STATELEN,
                (struct random_data *)&randData);
    

    ?

    【讨论】:

    • +1 而且,除非你真的必须,否则不要施放;否则,它只会阻止编译器帮助您解决此类错误。
    【解决方案3】:

    这个问题看起来非常相似:

    http://www.linuxquestions.org/questions/programming-9/crash-in-initstate_r-408757/

    另见:

    http://lists.debian.org/debian-glibc/2006/01/msg00037.html

    和:

    http://lists.debian.org/debian-glibc/2005/08/msg00492.html

    该函数的手册页很难理解,但似乎 rand_data 应该在传递给 initstate_r 之前进行初始化

    【讨论】:

      【解决方案4】:

      我遇到了同样的困难,它通过将 state 和 rand_data 都设为 0 来工作,在你的情况下,删除缓冲区前面的 &:

      char randomStateBuffer[STATELEN];
      struct random_data randData;
      memset(randomStateBuffer, 0, sizeof(randomStateBuffer));
      memset(&randData, 0, sizeof(struct random_data));
      initstate_r(time(NULL), randomStateBuffer,sizeof(randomStateBuffer), &randData);
      

      为我工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-27
        • 2019-10-24
        • 2011-07-07
        • 2022-01-23
        • 2016-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多