开发者

C++ LPTSTR to int (but memory overwrite problem using atoi)

I have the following code, m_edit is a MFC CEdit (I know I would never use MFC but project demanded it).

It's a simple loop, that gets the text from a text edit, converts it to integer after getting the first line, then stores it in m_y vector.

LPTSTR szTemp;
vector<int> m_y;
for(int i = 0; i < m_edit->GetLineCount(); i++){
  szTemp = s_y.GetBuffer(0); 
  m_edit->GetLine(i, szTemp); // get line text store in szTemp
  y = atoi(szTemp);
  m_y.push_back(y);
  szTemp = "";
  y = 0;
 }

IMPORTANT EXAMPLE: So let's say the CEdit has 6 numbers:

  • 0
  • 5
  • 2
  • 5
  • 18
  • 6

If you use Visual Studio's debugger you will notice an anomaly!! Here's what it shows:

  • y = 0
  • y = 5
  • y = 2
  • y = 5
  • y = 18
  • y = 68

Do you see that? szTemp when inserted into atoi, it returns the number 6, but concatenates the 2nd digit of the last number!!! This is why I did szTemp = "";, but the problem persists. Also, let's say the last number was 17 (not 18), then this time debugger would say y = 67, so it is definitely this problem.

However, Visual Studio deb开发者_运维百科ugger, when you hover over szTemp during this iteration, it says '6' <--- not '68' inside szTemp. So somehow atoi is ruining it.

Am I suppose to concatenate a \0 into szTemp before putting it into atoi? How do I solve this easily?


From the MFC CEdit::GetLine documentation:

Remarks: The copied line does not contain a null-termination character.

So you need to pay attention to GetLine's return value to determine how many bytes were copied into the buffer and then add your own NUL-terminator.

Also, I would recommend that you pass in the buffer size to make sure you don't have a potential buffer overflow.


I think you should specify a buffer size for GetBuffer

e.g.

szTemp = s_y.GetBuffer(MY_MAX_STRLEN);

having GetBuffer(0) allocates a 0 sized buffer since CString is (presumably) empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜