CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Jun 2003
    Posts
    188

    getenv() crashes

    if I do a getenv("windir") and windir does not exist getenv crashes. Is there a way around this?

  2. #2
    Join Date
    May 2004
    Posts
    45

    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;
        }
    }

  3. #3
    Join Date
    Jun 2003
    Posts
    188

    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

  4. #4
    Join Date
    Oct 2004
    Posts
    78

    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?????]

  5. #5
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    Re: getenv() crashes

    Why would the program crash if you tried to assign a null ppinter to a string?

  6. #6
    Join Date
    Apr 1999
    Posts
    27,449

    Re: getenv() crashes

    Quote 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
  •  





Click Here to Expand Forum to Full Width

Featured