我一直在编写一个“字节缓冲区”实用程序模块——只是一组供个人在低级开发中使用的函数。
不幸的是,当我的ByteBuffer_Append(...)
函数在结尾处为空终止字符时,我的函数无法正常工作,和/或为空终止字符增加了额外的空间。尝试此操作时的一个结果是,当我调用printf()
缓冲区的数据((char*)
执行强制转换)时:我将只获得字符串的一部分,因为将找到缓冲区中的第一个空终止字符。
所以,我正在寻找的是一种在函数中合并某种空终止功能的方法,但我有点想知道什么是解决这个问题的好方法,并且可以使用指向正确的方向。
这是代码,如果有帮助的话:
void ByteBuffer_Append( ByteBuffer_t* destBuffer, uInt8* source, uInt32 sourceLength )
{
if ( !destBuffer )
{
puts( "[ByteBuffer_Append]: param 'destBuffer' received is NULL, bailing out...\n" );
return;
}
if ( !source )
{
puts( "[ByteBuffer_Append]: param 'source' received is NULL, bailing out...\n" );
return;
}
size_t byteLength = sizeof( uInt8 ) * sourceLength;
// check to see if we need to reallocate the buffer
if ( destBuffer->capacity < byteLength || destBuffer->length >= sourceLength )
{
destBuffer->capacity += byteLength;
uInt8* newBuf = ( uInt8* ) realloc( destBuffer->data, destBuffer->capacity );
if ( !newBuf )
{
Mem_BadAlloc( "ByteBuffer_Append - realloc" );
}
destBuffer->data = newBuf;
}
uInt32 end = destBuffer->length + sourceLength;
// use a separate pointer for the source data as
// we copy it into the destination buffer
uInt8* pSource = source;
for ( uInt32 iBuffer = destBuffer->length; iBuffer < end; ++iBuffer )
{
destBuffer->data[ iBuffer ] = *pSource;
++pSource;
}
// the commented code below
// is where the null termination
// was happening
destBuffer->length += sourceLength; // + 1;
//destBuffer->data[ destBuffer->length - 1 ] = '\0';
}
非常感谢任何对此提供意见的人。