0

请注意,我正在使用 C++ 编译器(因此,对calloc函数调用进行强制转换)来执行此操作,但代码本质上是 C。

基本上,我有typedef一个unsigned char已知的 as viByte,我用它来创建一个字符串缓冲区来解析二进制文件(确切地说是一个 TGA 文件 - 但是,这无关紧要)。

我现在正在为它编写基本功能;追加、前置、新建等

问题是,在第一个循环的第一次迭代中viByteBuf_Prepend,我遇到了分段错误。我需要确切地知道为什么,因为这可能会让我在没有一些指示的情况下整晚都睡不着觉(双关语)。

我还想知道我的算法在缓冲区如何预先挂起字符串方面是否正确viByte。例如,我觉得使用memset太多可能不是一个好主意,而且我的 unsigned char 的 printf 格式是否正确(我觉得它不是,因为没有任何东西输出到我的控制台)。

在 GCC、Linux 上编译。

泽码

#ifdef VI_BYTEBUF_DEBUG
void viByteBuf_TestPrepend( void )
{
    viByteBuf* buf = viByteBuf_New( 4 );

    buf->str = ( viByte* ) 0x1;

    printf(" Before viByteBuf_Prepend => %uc ", buf->str);

    viByteBuf_Prepend( buf, 3, ( viByte* ) 0x2 );

    printf(" After viByteBuf_Prepend => %uc ", buf->str);
}
#endif

viByteBuf* viByteBuf_New( unsigned int len )
{
    viByteBuf* buf = ( viByteBuf* ) calloc( sizeof( viByteBuf ), 1 );

    const int buflen = len + 1;

    buf->str = ( viByte* ) calloc( sizeof( viByte ), buflen );
    buf->len = buflen;

    buf->str[ buflen ] = '\0';

    return buf;
}

void viByteBuf_Prepend( viByteBuf* buf, unsigned int len, viByte* str )
{
    unsigned int pos, i;
    const unsigned int totallen = buf->len + len;
    viByteBuf* tmp = viByteBuf_New( totallen );
    viByte* strpos = buf->str;


    memset( tmp->str, 0, tmp->len );

    int index;

    for( i = 0; i < buf->len; ++i )
    {

       index = ( buf->len - i ) - 1;

       *strpos = buf->str[ 0 ];
       ++strpos;
    }

    memset( buf->str, 0, buf->len );

    printf( "%uc\n", buf->str );

    i = totallen;

    for ( pos = 0; pos < len; ++pos )
    {
        tmp->str[ pos ] = str[ pos ];
        tmp->str[ i ]   = buf->str[ i ];

        --i;
    }

    memset( buf->str, 0, buf->len );

    buf->len = tmp->len;

    memcpy( buf->str, tmp->str, tmp->len );

    viByteBuf_Free( tmp );

    //memset(  )
    //realloc( ( viByteBuf* ) buf, sizeof( viByteBuf ) * tmp->len );
}

非常感谢。

更新

抱歉,我应该明确发布分段错误所在的代码。它就在这里:

for( i = 0; i < buf->len; ++i )
{

   index = ( buf->len - i ) - 1;

   *strpos = buf->str[ 0 ]; //<--segmentation fault.
   ++strpos;
}
4

1 回答 1

0

在你的代码上你有buf->str[ buflen ] = '\0';,但你只为buflen. 我想你的意思是buf->str[ len ] = '\0';

于 2012-03-05T08:37:19.353 回答