当释放已分配的内存时程序崩溃:“在Y处修改的堆块在Y处理请求的大小为21”。
运行函数getUstr,在free(uStr)上崩溃。 有人可以帮我找到我在哪里使用未分配的内存吗? 谢谢!
int HexToUChars(char* hexStr, unsigned char **str){
int i, n;
int strLen = strlen(hexStr)/2;
for (i = 0; i < (int)strLen; i++) {
sscanf_s(hexStr + 2 * i*sizeof(unsigned char), "%02X", *str+i*sizeof(unsigned char));
}
return 0;
}
int getUStr(){
char *hexStr = "E7CA7905DD060F0E437C885BF13DED9243B1D2BD94CB11223DA71360A8F7D2D4";
unsigned char *uStr;
size_t strLen = (size_t)strlen(hexStr) / 2;
uStr = calloc((strLen + 1), sizeof(unsigned char));
if (uStr != NULL){
HexToUChars(hexStr, &uStr);
free(uStr);//Error : Heap block at X modified at Y past requested size of 21
}
}
答案 0 :(得分:0)
对于sscanf()
和朋友,%02X
需要指向unsigned int
的指针,但您指的是指向unsigned char
的指针。如果您的系统上有一个unsigned int
,例如4个字节,那么您将通过该循环在最后几次迭代中写入已分配内存的末尾。
您应该提供指向(本地)unsigned int
到sscanf_s()
的指针,然后将其值分配给您的unsigned char
。
答案 1 :(得分:0)
there were several errors in the presented code.
those errors are fixed here
I did add a few $includes, etc so the file would compile
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int HexToUChars( const char *, unsigned char * );
int getUStr( void );
int HexToUChars(const char* pHexStr, unsigned char *pStr)
{
int i = 0; // loop index
//int n; // this raises a compiler warning about unused variable
// the strLen is using a reserved word, with only a capitalization change,
// I.E. very poor program practice
int hexStrLen = (int)strlen(pHexStr) >> 1; // this assumes that hexStr is an even number of bytes
for (i = 0; i < hexStrLen; i++)
{
pStr[i] = pHexStr[2*i] - '0';
pStr[i] += pHexStr[(2*i)+1] - '0';
} // end for
return 1;
} // end function: HexToUChars
int getUStr()
{
const char* pHexStr = "E7CA7905DD060F0E437C885BF13DED9243B1D2BD94CB11223DA71360A8F7D2D4";
unsigned char *pStr;
int hexStrLen = strlen(pHexStr) / 2;
if( NULL == (pStr = calloc( (hexStrLen + 1), sizeof(unsigned char) ) ) )
{
perror( "calloc failed" );
exit( EXIT_FAILURE );
}
// implied else, calloc successful
HexToUChars(pHexStr, pStr);
if( strlen((const char*)pStr) != hexStrLen )
{
perror( "problem in HexToUChars");
}
printf( "%s", pStr );
free(pStr);
return(0); // without this, compiler raises warning about no return statement
}