Nicholas Nicholas - 1 month ago 8
C++ Question

Critical Error When Copying From char* to char* Using Custom String Copy Function

char** strSplit(const char* str, const char splitter)
{
unsigned long splitterCount = strSplitCount(str, splitter) + 1;

char** result = new char*[splitterCount];

unsigned long startRange = 0, endRange = 0;
for (unsigned long i = 0; i < splitterCount; i++)
{
while (str[endRange] == splitter)
{
endRange++;
startRange++;
}
while (str[endRange] != splitter && str[endRange] != '\0')
{
endRange++;
}

result[i] = new char[(endRange - startRange + 1)];

strCopy(result[i], str);

// unsigned long indexOffset = 0;
// for (unsigned long j = startRange; j < endRange; j++)
// {
// if (str[j] != splitter)
// {
// result[i][indexOffset] = str[j];
// }
// indexOffset++;
// }
// result[i][indexOffset] = '\0';
//
// startRange = ++endRange;
}

return result;
}


This function takes in a const char* of a cstring and a const char of where to split within the string. The function correctly splits strings into a char** and returns it. To make the function look cleaner I made a strCopy function which works correctly outside this fucntion. But when strCopy is used within the function visual studio throws a critical error. But to make things even more interesting if you uncomment the commented code and remove the strCopy function the data gets copied correctly and no error is thrown. So why does my strCopy function not work?

void strCopy(char* dest, const char* src)
{
while (*src)
{
*dest = *src;
src++;
dest++;
}
*dest = '\0';
}

Answer

Look at this statement

result[i] = new char[(endRange - startRange + 1)];

It is clear that you need to copy str from startRange up to endRange and append the result string with the terminating zero.

However you are trying to copy all the string str.

strCopy(result[i], str);

You need to write a function either like std::strncpy or like std::memcpy and use it to copy substrings.