-
October 27th, 2004, 03:05 PM
#1
getenv() crashes
if I do a getenv("windir") and windir does not exist getenv crashes. Is there a way around this?
-
October 27th, 2004, 04:11 PM
#2
Re: getenv() crashes
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;
}
}
-
October 28th, 2004, 12:53 PM
#3
Re: getenv() crashes
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
-
October 28th, 2004, 01:20 PM
#4
Re: getenv() 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?????]
-
October 28th, 2004, 04:12 PM
#5
Re: getenv() crashes
Why would the program crash if you tried to assign a null ppinter to a string?
-
October 28th, 2004, 05:12 PM
#6
Re: getenv() crashes
Originally Posted by HighCommander4
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.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|