andrew
andrew

Reputation: 39

Why is my code throwing a C6386 error when trying to copy a character array?

i am getting a c++ warning C6386 on the following code:

int m_wordNumber = getRandomNumber();
//get word size
size_t m_wordSize = strlen(m_wordsArray[m_wordNumber]);
//create word arrays
char* m_chosenWord = new char[m_wordSize];
char* m_blankArray = new char[m_wordSize];

int m_incorrectGuessCounter = 0;

generateArray(m_blankArray, m_wordSize);
//copy word to new array
strcpy_s(m_chosenWord, m_wordSize + 1, m_wordsArray[m_wordNumber]);
//create temp array and output word
char * m_tempWordHolder = nullptr;
std::cout << m_chosenWord << std::endl;

The line that is throwing the warning is the strcpy_s line, all it's trying to do is copy a string from a character array to a different character array.

Any help would be greatly appreciated, thanks.

the warning is as follows:

Warning C6386 Buffer overrun while writing to 'm_chosenWord': the writable size is 'm_wordSize*1' bytes, but '7' bytes might be written

Upvotes: 0

Views: 639

Answers (1)

ChrisMM
ChrisMM

Reputation: 10021

When you allocate m_chosenWord, you allocate m_wordSize characters. However, in

strcpy_s(m_chosenWord, m_wordSize + 1, m_wordsArray[m_wordNumber]);

You are writing m_wordSize + 1 characters. In the initial allocation, you want to add the +1 as well.

Upvotes: 4

Related Questions