Search code examples
c++segmentation-faultatoi

Segfault in atoi(str)


I'm new to the C/C++ game so I assume I'm making a rookie mistake:

int main(){
  char* clen;
  clen = getenv("CONTENT_LENGTH");
  if (clen==NULL){
    cout << "No such ENV var: CONTENT_LENGTH"<<endl;
    exit(0);
  }
  int cl = 0; 
  cl = atoi(clen);
  if (cl < 1){
    return inputPage();
  }

  // if there is no content, we assume that this is a fresh request, 
//   so we showed the input page, otherwise, we'll return dispatch to 
  //the processing code.
  postTest(clen);

}

This is supposed to be a CGI script. As far as I can tell with GDB, print statements, etc. this code segfaults on the line "cl = atoi(clen);" I have no idea why this is. K&R suggests that this is correct. I basically copied this line from a half dozen other online tutorials. And it seemed to be working last night! I'm totally stumped.


Solution

  • I don't believe that it really crashes on atoi()

    Could you please try out this code?

    #include <iostream>
    #include <stdlib.h>
    #ifndef NULL
    #define NULL 0
    #endif
    
    using namespace std;
    
    int main(){
      char* clen;
      clen = getenv("CONTENT_LENGTH");
      if (clen==NULL){
        cout << "No such ENV var: CONTENT_LENGTH"<<endl;
        exit(0);
      }
      int cl = 0;
      cl = atoi(clen);
      if (cl < 1){
                        std::cout << "return inputPage();" << std::endl;
                        return 0;
      }
    
        std::cout << "postTest();" << std::endl;
    
    }
    

    compile it e.g. to "app" and run it with some variations of CONTENT_LENGTH, e.g.

    ./app
    CONTENT_LENGTH=4 ./app
    CONTENT_LENGTH=-4 ./app
    CONTENT_LENGTH=a ./app