首页 文章

C,atoi()生成分段错误

提问于
浏览
-1

我正在使用atoi()从头部获取状态代码,但它不能使用以下输入:

" 404 Not Found\r\nContent-type: text/html\r\nDate: Thu, 12 Dec 2013 20:53:22 GMT\r\nConnection: close\r\n\r\n"

Shouldn't it stop reading at the first non-numerical character? 如上所述:http://www-control.eng.cam.ac.uk/~pcr20/www.cppreference.com/stdstring_details.html

一旦读取了非数字字符,> atoi()将停止从str读取

根据调试器,发生分段错误的代码:

__NTH (atoi (const char *__nptr))
{
   return (int) strtol (__nptr, (char **) NULL, 10);
}

它是来自stdlib.h的第280行,__nptr的值是:

__nptr  " 404 Not Found\r\nContent-type: text/html\r\nDate: Thu, 12 Dec 2013 20:53:22 GMT\r\nConnection: close\r\n\r\n" char *

I would like to point out that the following inputs work fine (no segmentation fault):

__nptr  " 404 Not Found\r\nContent-Type: text/html; charset=UTF-8\r\nX-Content-Type-Options: nosniff\r\nDate: Thu, 12 Dec 2013 21:13:24 GMT\r\nServer: sffe\r\nContent-Length: 943\r\nX-XSS-Protection: 1; mode=block\r\nAlternate-Protocol: 80:quic\r\n\r\n"   char *

__nptr  " 302 Found\r\nCache-Control: no-cache, no-store, must-revalidate\r\nPragma: no-cache\r\nExpires: 0\r\nLocation: http://br.godaddy.com/\r\nServer: Microsoft-IIS/7.0\r\nSet-Cookie: MemBotChk=false; path=/\r\nSet-Cookie: countrysite1=www; domain=godaddy.com; expires=Fri, 12-Dec-2014 21:15:09 GMT; path=/\r\nSet-Cookie: language1=pt-BR; domain=godaddy.com; expires=Fri, 12-Dec-2014 21:15:09 GMT; path=/\r\nP3P: policyref="/w3c/p3p.xml", CP="COM CNT DEM FIN GOV INT NAV ONL PHY PRE PUR STA UNI IDC CAO OTI DSP COR C..."    char *

实际上,到目前为止所有输入都可以正常工作,除了我在开头提到的那个 . What could be causing segmentation fault?

删除前导空格不是 atoi() ,而是其他内容 . 如何识别问题?


Valgrind results:

main.c中的main读取大小为1:23

地址0xf没有堆叠,malloc'd或(最近)free'd

  • 1:__strtol_l_internal in /build/eglibc-hkB3nk/eglibc-2.17/stdlib/../stdlib/strtol_l.c:298

  • 2:/usr/include/stdlib.h:280中的get_web_content

  • 3:main在main.c:23

main.c:23只是对get_web_content()的调用


The problem was that atoi() was called with a null pointer later.

1 回答

  • 1

    这真是一个初学者的错误 . 为了为响应体分配内存,我调用了strcasestr来查找Content-Length:字段 . 只有我没有检查是否找到了该字段 . 我没有得到的是为什么调试器显示以前对atoi()的调用 .

    In case anyone with the same problem happens to stumble upon this question here's what I was doing wrong:

    fill_this->content_length = atoi(strcasestr(header_string + i, "Content-Length:") + 15);
    

    而解决方案:

    char *temp = strcasestr(header_string + i, "Content-Length:");
    if(temp == NULL)
       return;
    fill_this->content_length = atoi(temp + 15);
    

相关问题