Re: Problem with using char* to return string by reference
swtbase@gmail.com wrote:
I have a problem using char* in C++.
My code looks like this:
void ReadInitRegVal(char* a, char* b, float& c, float& d)
{
HKEY hKey;
DWORD DataSize;
BYTE temp[256];
RegOpenKeyEx(HKEY_CURRENT_USER, REGDATASTOREKEY, 0, KEY_READ, &hKey);
DataSize = 256;
RegQueryValueEx(hKey, "Data0", 0, NULL, temp, &DataSize);
strcpy(a, (char*)temp);
DataSize = 20;
RegQueryValueEx(hKey, "Data1", 0, NULL, temp, &DataSize);
strcpy(b, (char*)temp);
DataSize = 20;
RegQueryValueEx(hKey, "Data2", 0, NULL, temp, &DataSize);
c = (float)atof((char*)temp);
DataSize = 20;
RegQueryValueEx(hKey, "Data3", 0, NULL, temp, &DataSize);
d = (float)atof((char*)temp);
RegCloseKey(hKey);
}
int main()
{
char a[256];
char b[8];
float c;
float d;
ReadInitRegVal(a, b, c, d);
cout << a << '\n' << b << '\n' << c << '\n' << d << '\n';
return 0;
}
The program displays values b, c and d correctly but displays nothing
in place of a (null value to be correct). On checking, a[0 to 8] gives
output ' n t e l L A N ' (String to be read is 'Intel LAN Adapter'.
'Cout'ing temp and a (local to func ReadInitRegVal()) has correct
values but the returned a (local to main()) has corrupted. Why is this
so?
swtbase:
I see
int main()
{
// ...
char b[8];
// ...
}
void ReadInitRegVal(char* a, char* b, float& c, float& d)
{
// ...
DataSize = 20;
RegQueryValueEx(hKey, "Data1", 0, NULL, temp, &DataSize);
strcpy(b, (char*)temp);
// ...
}
I'm not sure this is your problem, but you have a potential buffer over-run here.
--
David Wilkinson
Visual C++ MVP