Segfault in atoi (str)

I am new to C / C ++, so I assume I will make 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, printed statements, etc., This segfaults code 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 half a dozen other online lessons. And it looks like he worked last night! I am completely at a dead end.

+3
source share
4 answers

I do not believe that it really crashes on atoi ()

Could you try 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;

}

, . "" CONTENT_LENGTH, .

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

getenv() , , segfault cl = atoi(clen). , getenv() NULL, ( C).

NULL , ( "script" ) - .

: , ? HTTP 500? , cout << "Content-type: text/html\n\n". -?

EDIT2: , C, atoi(), ; ++ lexical_cast ( TR1 boost).

+1

, GDB. () atoi(), , ? , , atoi()?

0

, atoi ++ . , CGI, CONTENT_LENGTH GET, . , , . inputPage, , CONTENT_LENGTH .

0

Source: https://habr.com/ru/post/1726186/


All Articles