Project

General

Profile

segmentation fault using resource

Added by Bruno Zerbo almost 5 years ago

Hi,

I'm trying this simple application to learn to use WResource but I get a segmentation fault using WServer::addResource

here the code:

#include <Wt/WServer.h>
#include <Wt/WResource.h>
#include <Wt/Http/Request.h>
#include <Wt/Http/Response.h>

using namespace Wt;

class MyResource : public Wt::WResource
{
public:
    MyResource()
    {
        suggestFileName("data.txt");
    }
    ~MyResource() {
        beingDeleted();
    }
    void handleRequest(const Wt::Http::Request& request,
                       Wt::Http::Response& response) {
        response.setMimeType("plain/text");
        response.out() << "I am a text file." << std::endl;
    }
};

int main(int argc, char **argv)
{
    try {

        Wt::WServer server(argv[0]);

        server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);

        server.addEntryPoint(Wt::EntryPointType::Application,  [](const Wt::WEnvironment &env) {
            return Wt::cpp14::make_unique<Wt::WApplication>(env);
        });

        MyResource *resource;
        server.addResource(resource,"/risorsa");             //SEGMENTATION FAULT HERE

        if (server.start()) {
            int sig = WServer::waitForShutdown();
            std::cerr << "Shutdown (signal = " << sig << ")" << std::endl;
            server.stop();
        }
    } catch (WServer::Exception& e) {
        std::cerr << e.what() << "\n";
        return 1;
    } catch (std::exception& e) {
        std::cerr << "exception: " << e.what() << "\n";
        return 1;
    }
}

I think that the problem is in my configuration file...

can you give me some hint?

Thank you,

Bruno


Replies (3)

RE: segmentation fault using resource - Added by Ockert van Schalkwyk over 4 years ago

Your MyResource seems uninitialized, try something like the following

...
int main(int argc,char **argv){
        return Wt::WRun(
        argc,
        argv,[](const Wt::WEnvironment&amp; env){
            ...
            app-&gt;root()-&gt;addNew&lt;HelloTemplate&gt;();
            env.server()-&gt;addResource(new MyResource,"test");
            return app;
        }
    );
    return 0;
}

RE: segmentation fault using resource - Added by Ockert van Schalkwyk over 4 years ago

Also, you need to ensure that the resource is only added once, probably with removeEntryPoint()

RE: segmentation fault using resource - Added by Roel Standaert over 4 years ago

Ockert: the resource can be perfectly created outside of the application creator.

This should work:

MyResource resource;
server.addResource(&resource,"/risorsa");

Because the resource is on the stack, it also won't leak. There's no risk of use after free because waitForShutdown() will block, and WServer::stop() will make sure no requests will arrive for that resource anymore.

    (1-3/3)