これを行うために C++ コンパイラ (したがって、calloc
関数呼び出しのキャスト) を使用していますが、コードは基本的に C です。
基本的に、私はとして知られtypedef
ている を持っています。これを使用して、バイナリからファイルを解析するための文字列バッファーを作成しています (正確には TGA ファイルですが、それは関係ありません)。unsigned char
viByte
私は今、そのための基本的な関数を書いています。append、prepend、new など。
問題は、 の最初のループの最初の繰り返しでviByteBuf_Prepend
、セグメンテーション違反が発生することです。理由を正確に知る必要があります。これは、いくつかのヒントがなくても一晩中眠れなくなる可能性があるためです (しゃれが意図されています)。
また、バッファが文字列をどのように保留しているかという点で、私のアルゴリズムが正しいかどうかも知りたいです。viByte
たとえば、使いmemset
すぎるのは悪い考えかもしれないし、unsigned char の printf 形式が正しいかどうか (コンソールに何も出力されていないため、そうではないと感じています)。
GCC、Linux でのコンパイル。
Zeコード
#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;
}