0

I'm trying to write my own function in order to substring a given pointer to chars array, by a given length and start index.

When I execute the code, i'm getting an error "Debug Assertion Failed". The program failes in "tcscpy_s.inl" (Expression: L"Buffer is too small" && 0)

This is my code:

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;
}

How can I solve this problem?

Aviv
  • 456
  • 1
  • 7
  • 16

2 Answers2

2

The buffer size does not include space for terminating 0 (although allocation is done correctly). Try

strcpy_s(StrToRet, Length + 1, OriginalString);
AlexD
  • 32,156
  • 3
  • 71
  • 65
0

Try allocate more memory for StrToRet. Make shure that StartIndex and Length non-negative number and OriginalString correct null terminated string.

Artsiom Miksiuk
  • 3,896
  • 9
  • 33
  • 49