Page 1 of 1

SegFault on GetInputStream

Posted: Wed Nov 23, 2011 5:02 am
by FlyingIsFun1217
Greetings,

After many years of inactivity, I've decided to try my hand at programming again.

To the point: I've been working on a simple HTTP GET request to youtube, attempting to get an XML document through their fairly simple API. When I go to use wxHTTP::GetInputStream though, I get (with certain regularity) a Segmentation fault.

Code below:

Code: Select all

wxString wxGETRequest(wxString pageDir)
{
    wxString response = wxEmptyString;

    wxHTTP request;
    request.Connect(wxT("gdata.youtube.com"));
    wxInputStream *serverStream = request.GetInputStream(pageDir);

    if(request.GetError() == wxPROTO_NOERR)
    {
        wxStringOutputStream outputStream(&response);
        serverStream -> Read(outputStream);
    }

    else response = wxEmptyString;

    wxDELETE(serverStream);
    request.Close();

    return response;
}

int main()
{
    string      Query;
    wxString    wxQuery;
    wxString    wxQueryURI;

    cout << "Enter search term: ";

    getline(cin, Query);

    wxQuery = wxQuery.FromAscii(Query.c_str());
    wxQuery.Replace(wxT(" "), wxT("+"), true);

    wxQueryURI = wxT("/feeds/api/videos?q=") + wxQuery + wxT("&max-results=10&v=2");

    cout << endl << wxQueryURI.ToAscii() << endl << endl;

    wxString searchResponseString = wxGETRequest(wxQueryURI);

    cout << endl << searchResponseString << endl;
}
Is this normal behavior? Something to do with not having any type of actual GUI in the program?

Program output:
Enter search term: test

/feeds/api/videos?q=test&max-results=10&v=2

Segmentation fault
Thanks for the help!
FlyingIsFun1217

Re: SegFault on GetInputStream

Posted: Wed Nov 23, 2011 9:11 am
by doublemax
If you use wxWidgets from main() without an wxApp object, you need to initialize wxWidgets first. You can do this by wrapping wxInitialize()/wxUninitialize() calls around your code, or by creating an instance of wxInitializer (which does the same internally).
http://docs.wxwidgets.org/stable/wx_app ... initialize

Are you sure that the call to GetInputStream() crashes? I would have expected that GetInputStream() returns NULL (for whatever reason) and that the following code crashes, because you didn't check the pointer for NULL.

Re: SegFault on GetInputStream

Posted: Wed Nov 23, 2011 4:45 pm
by FlyingIsFun1217
Yep, that did the trick, thanks!

Also, I had pinpointed it down to that one line by commenting everything else out in the wxGETRequest function.

FlyingIsFun1217