我正在尝试编写自己的函数,以便按给定的长度和起始索引对给定的字符数组指针进行子字符串化。
当我执行代码时,出现错误“调试断言失败”。程序在 "tcscpy_s.inl"(Expression: L"Buffer is too small"&& 0)
中失败这是我的代码:
char* String_Substring(char* OriginalString, int StartIndex, int Length)
{
// Allocate space for the new string by it's given length.
char* StrToRet = (char*)malloc((Length + 1) * sizeof(char));
// Move to the start position of the sub - string.
OriginalString += StartIndex;
// Copy the requested sub - string to 'StrToRet'
strcpy_s(StrToRet, Length, OriginalString);
return StrToRet;
}
我该如何解决这个问题?
最佳答案
缓冲区大小不包括用于终止 0
的空间(尽管分配已正确完成)。尝试
strcpy_s(StrToRet, Length + 1, OriginalString);
关于c - 尝试创建子字符串时断言失败错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26368647/