gpt4 book ai didi

c++ - C/C++ 中的 C 风格无符号字符解析和操作 - 段错误

转载 作者:行者123 更新时间:2023-11-30 18:01:51 24 4
gpt4 key购买 nike

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

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

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

问题是,在 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;
}

最佳答案

在您的代码中,您有 buf->str[ buflen ] = '\0';,但您仅为 buflen 分配空间。我认为你的意思是 buf->str[ len ] = '\0';

关于c++ - C/C++ 中的 C 风格无符号字符解析和操作 - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9563365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com