除非通过gdb运行,​​如何调试段错误的代码?

时间:2010-07-09 10:17:57

标签: python gdb segmentation-fault

这是一个单线程代码。

特别是:ahocorasick Python扩展模块(easy_install ahocorasick)。

我将问题分解为一个简单的例子:

import ahocorasick
t = ahocorasick.KeywordTree()
t.add("a")

当我在gdb中运行它时,一切都很好,当我将这些指令输入Python CLI时也会发生同样的情况。但是,当我尝试定期运行脚本时,我会遇到一个段错误。

为了使它更奇怪,导致segfault的行(由核心转储分析识别)是一个常规的int增量(参见函数体的底部)。

我完全被这一刻困住了,我该怎么办?

int
aho_corasick_addstring(aho_corasick_t *in, unsigned char *string, size_t n)
{
    aho_corasick_t* g = in;
    aho_corasick_state_t *state,*s = NULL;
    int j = 0;

    state = g->zerostate;

    // As long as we have transitions follow them
    while( j != n &&
           (s = aho_corasick_goto_get(state,*(string+j))) != FAIL )
    {
        state = s;
        ++j;
    }

    if ( j == n ) {
        /* dyoo: added so that if a keyword ends up in a prefix
           of another, we still mark that as a match.*/
        aho_corasick_output(s) = j;
        return 0;
    }

    while( j != n )
    {
        // Create new state
        if ( (s = xalloc(sizeof(aho_corasick_state_t))) == NULL )
            return -1;
        s->id = g->newstate++;
        debug(printf("allocating state %d\n", s->id)); /* debug */ 
        s->depth = state->depth + 1;

        /* FIXME: check the error return value of
           aho_corasick_goto_initialize. */
        aho_corasick_goto_initialize(s);

        // Create transition
        aho_corasick_goto_set(state,*(string+j), s);
        debug(printf("%u -> %c -> %u\n",state->id,*(string+j),s->id));
        state = s;
        aho_corasick_output(s) = 0;
        aho_corasick_fail(s) = NULL;
        ++j;                                 // <--- HERE!
    }

    aho_corasick_output(s) = n;

    return 0;
}

2 个答案:

答案 0 :(得分:2)

您可以使用其他工具来查找不一定会导致程序崩溃的错误。 valgrindelectric fencepurifycoveritylint - 类似工具可以为您提供帮助。

在某些情况下,您可能需要构建自己的python才能使用它。另外,对于内存损坏的事情,有一种可能性让python使用直接内存分配而不是pythons所拥有的(或者曾经没有构建过它们)。

答案 1 :(得分:0)

您是否尝试将while循环转换为for循环?如果你使用更直观的东西,可能会对++j产生一些微妙的误解。