废话不多说,在一个函数里出现了上述问题,出现问题的代码如下:
char * newUrl=new char[urlEndPos-urlStartPos+1];
sscanf(urlStartPos,"%[^\"]",newUrl);
string tempUrl=newUrl;
最后会delete newUrl的。
每次运行到string tempUrl=newUrl; 这里就出错,出错的具体信息如下:
*** Error in `/home/zieng/Desktop/spider': malloc(): memory corruption: 0x000000000060a520 ***
Program received signal SIGABRT, Aborted.
0x00007ffff7530cc9 in __GI_raise (sig=sig@entry=6)
at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56 ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0 0x00007ffff7530cc9 in __GI_raise (sig=sig@entry=6)
at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#1 0x00007ffff75340d8 in __GI_abort () at abort.c:89
#2 0x00007ffff756df24 in __libc_message (do_abort=1,
fmt=fmt@entry=0x7ffff767c6c8 "*** Error in `%s': %s: 0x%s ***\n")
at ../sysdeps/posix/libc_fatal.c:175
#3 0x00007ffff757bac6 in malloc_printerr (ptr=0x60a520,
str=0x7ffff767883a "malloc(): memory corruption", action=<optimized out>)
at malloc.c:4996
#4 _int_malloc (av=0x7ffff78b9760 <main_arena>, bytes=72) at malloc.c:3447
#5 0x00007ffff757d340 in __GI___libc_malloc (bytes=72) at malloc.c:2891
#6 0x00007ffff7b34f2d in operator new(unsigned long) ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7 0x00007ffff7b903b9 in std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#8 0x00007ffff7b91ae1 in char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#9 0x00007ffff7b91ef8 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#10 0x000000000040297b in html_parse (content=..., imgUrl=...)
at spider_v2.0.cpp:253
#11 0x0000000000402cc4 in BFS (url=...) at spider_v2.0.cpp:312
#12 0x0000000000401e36 in main (argc=1, argv=0x7fffffffdf68)
at spider_v2.0.cpp:78
(gdb) frame 10
#10 0x000000000040297b in html_parse (content=..., imgUrl=...)
at spider_v2.0.cpp:253
253 const string tempUrl=newUrl;
(gdb) p tempUrl
$1 = {static npos = <optimized out>,
_M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>},
_M_p = 0x7fffffffdd60 "\200\335\377\377\377\177"}}
(gdb) p newUrl
$2 = 0x60a500 "http://s9.qhimg.com/static/8a60aae81b5f422b.css"
可以看到,newUrl是没问题的,但是tempUrl就是npos,而:
npos is a static member constant value with the greatest possible value for an element of type size_t.
This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".
As a return value, it is usually used to indicate no matches.
这是怎么回事呢?
为什么从一个char数组转换string就出问题呢?