Newbie to C++ learning by converting a java program to c++. The following code results in a segmentation fault (SIGSEGV) when executed.
//add web page reference to pages queue (STL)
void CrawlerQueue::addWebPage(WebPage & webpage) {
pagesBuffer.push(webpage);
}
//remove and return web page reference from pages queue
WebPage & CrawlerQueue::getWebPage() {
if (pagesBuffer.size() > 0) {
WebPage & page = pagesBuffer.front();
pagesBuffer.pop();
return page;
} else
throw "Web pages queue is empty!";
}
//code that results in segmentation fault when called
void PageParser::extractLinks(){
try {
WebPage & page = crawlerqueue.getWebPage();
}catch (const char * error) {
return;
}
}
The changes to the above code that fix the segmentation fault issue are highlighted(<====):
//return a const WebPage object instead of a WebPage reference
const WebPage CrawlerQueue::getWebPage() { <====
if (pagesBuffer.size() > 0) {
WebPage page = pagesBuffer.front(); <====
pagesBuffer.pop();
return page;
} else
throw "Web pages queue is empty!";
}
//no segmentation fault thrown with modifications
void PageParser::extractLinks(){
try {
WebPage page = crawlerqueue.getWebPage(); <====
}catch (const char * error) {
return;
}
}
What gives? I'm still trying to understand references and pointers