【发布时间】:2014-12-09 17:01:48
【问题描述】:
我正在尝试编写自己的函数,以便将给定的指向 chars 数组的指针按给定的长度和起始索引进行子串化。
当我执行代码时,我收到一个错误“调试断言失败”。 "tcscpy_s.inl" 中程序失败(表达式: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;
}
我该如何解决这个问题?
【问题讨论】:
-
你确定这个代码段中出现了这个错误吗?您是否验证过内存确实被分配了?
-
可能不相关,但从技术上讲,您的 malloc 应该是
(Length + 1) * sizeof(char)。 -
@chuex 你说得对,我改了。
标签: c string malloc assertions strcpy