Vase Vase -4 years ago 112
C++ Question

Why is string.empty() evaluating to true when the string contains a value?

Introduction

I am making an application using mfc that has a dialog box used to sort data in a spreadsheet. The dialog contains several controls including edit boxes. when the user clicks the OK button, the dialog should retrieve their preferences and close.

Issue

When getting the information from the dialog boxes, the strings containing the information are always registering as empty. I set a breakpoint at the location that the strings are located at, and the values seem to be found fine, but when I call any function to determine the size of the strings, it shows as 0.

Code

std::string min;
std::string max;
MinEdit.GetWindowText(&min[0], 20);
MinVal = atof(min.c_str());

MaxEdit.GetWindowText(&max[0], 20);
MaxVal = atof(max.c_str());

if (min.empty())
{
AfxMessageBox(_T("Please Enter A Minimum Value"));
return;
}

if (max.empty())
{
AfxMessageBox(_T("Please Enter A Maximum Value"));
return;
}


Question

Why do these strings always register as empty? I checked their length, which is returned as zero, yet when I check MinVal and MaxVal they have the value that was entered into the edit box. How can these strings be able to initialize the other variables with a value, when they are showing as empty?

Answer Source

This is the error.

std::string min;
MinEdit.GetWindowText(&min[0], 20);

The string has no length, and you ask GetWindowText to write into that buffer. That's an overrun and it causes undefined behavior.

Instead, allocate some space in the string, then resize it afterwards:

std::string min;
min.resize(20);
min.resize(MinEdit.GetWindowText(&min[0], min.size()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download