简体   繁体   中英

vector::size and Segmentation fault

Why could this code throw segmentation fault?:/

listeners = new vector<Listener*> ();

... /* other code */

if (listeners != NULL) {
int i = listeners->size();
}

Just because the pointer isn't NULL doesn't mean it points to a valid vector<Listener*> object.

Run your program through valgrind to detect memory corruption issues, and make sure that you run your code through your debugger, too.

If you still have problems, post a test that reproduces the issue (rather than little snippets of code that do not).

Easier than using valgrind is to move the listeners->size() call right after the allocation and see if it segfaults even then. If no, move it a few lines of code lower and try again, repeat. If it segfaults, you just found the lines that cause it. Maybe you have done something with the pointer along the way and this is a method to find that piece of code. Look at the bisection method .

May not work always, it's more of a heuristic.

vector<Listener*> listeners; might save you some problems or make the reason of the code break more evident

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM