if I do a getenv("windir") and windir does not exist getenv crashes. Is there a way around this? :eek:
Printable View
if I do a getenv("windir") and windir does not exist getenv crashes. Is there a way around this? :eek:
getenv does not crash if the environment variable is not found: it returns NULL.
You need to test against NULL before using the result of "getenv" in your programs.
For instance:
Code:#include <cstdio>
#include <iostream>
using namespace std;
main () {
char *p = getenv("windir");
if (p != NULL) {
cout << p << endl;
}
}
Thanks,
Looks like when I assigned it to a string like this...
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
main () {
string p;
p= getenv("windir");
}
...if windir does not exist, it crashes
Because you must check the return value (which is a char *) before you can assign it to a string!
[didn't you read the previous response at all?????]
Why would the program crash if you tried to assign a null ppinter to a string?
It depends on how the string class is implemented. There is no guarantee that the string class handle NULL pointers, or any invalid pointer, with no errors. More than likely, the string is trying to read from the NULL pointer, and on many OSes, doing so can cause a program to crash.Quote:
Originally Posted by HighCommander4
Regards,
Paul McKenzie