pdm
pdm

Reputation: 1107

gdk_screen_get_default() and get_width()/height() segfault

I just cracked open Foundations of GTK Development and was trying to do something creative that would be useful in the future of the application I'm developing at work.

Specifically,

int main(int argc, char *argv[])
{
    GtkWidget *window = NULL, *label = NULL;
    GdkScreen *screen = NULL;
    gint width = 0, height = 0;
    char *resolution = NULL;

    gtk_init(&argc, &argv);

    if((screen = gdk_screen_get_default()) != NULL)
    {
        width  = gdk_screen_get_width(screen);
        height = gdk_screen_get_height(screen);
    }

    sprintf(resolution, "%d x %d", width, height);

    ...

causes a segfault when executed. I am certain that I'm making a noob mistake and that eventually I'll recognize the error for what it is, but at present I am unable to figure it out. The Google results I've been able to generate haven't been too useful either.

Any help?

Upvotes: 0

Views: 629

Answers (1)

Mark Wilkins
Mark Wilkins

Reputation: 41222

One problem is that the variable resolution points to NULL, so the sprintf to that will definitely result in undefined behavior (likely a crash). The code should either allocate memory for that variable (e.g., resolution = malloc(somesize);) or declare it on the stack (e.g., char resolution[somesize];)

Upvotes: 2

Related Questions