| Unix Content | Register | FAQ | Calendar | Search | Today's Posts | Mark Forums Read |
|
#1
|
| Dear All! I have the following code, which produces segmentation fault. Any reasons why? #include #include #include #include #include #include #include struct Server_class{ Display *dpy; Window win; Window root; Pixmap pm; GC gc; } *app; void setup_connection(){ app->dpy = XOpenDisplay(NULL); printf("Hello\n"); } int main(){ setup_connection(); return 0; } Thanks. |
|
#2
|
| On Sep 30, 9:49*am, eotcl > Dear All! > > I have the following code, which produces segmentation fault. > Any reasons why? > > #include > #include > #include > #include > #include > #include > #include > struct Server_class{ > Display *dpy; > * Window win; > * Window root; > * Pixmap pm; > * GC gc; > > } *app; > > void setup_connection(){ > * app->dpy = XOpenDisplay(NULL); > * printf("Hello\n"); > > } > > int main(){ > * setup_connection(); > * return 0; > > } > You have declared app as a pointer, but haven't pointed it to anything. Thus the dereference app->dpy is dereferencing an uninitialized pointer. -- Fred Kleinschmidt |
|
#3
|
| Fred > On Sep 30, 9:49*am, eotcl >> Dear All! >> >> I have the following code, which produces segmentation fault. >> Any reasons why? >> >> #include >> #include >> #include >> #include >> #include >> #include >> #include >> struct Server_class{ >> Display *dpy; >> * Window win; >> * Window root; >> * Pixmap pm; >> * GC gc; >> >> } *app; >> >> void setup_connection(){ >> * app->dpy = XOpenDisplay(NULL); >> * printf("Hello\n"); >> >> } >> >> int main(){ >> * setup_connection(); >> * return 0; >> >> } >> > > You have declared app as a pointer, but haven't pointed it to > anything. > Thus the dereference app->dpy is dereferencing an uninitialized > pointer. That's not entirely accurate. Since his pointer has file scope, it will be a null pointer when he dereferences it. Dereferencing a null pointer is obviously a bad thing to do. -- Måns Rullgård mans@mansr.com |
|
#4
|
| > You have declared app as a pointer, but haven't pointed it to > anything. > Thus the dereference app->dpy is dereferencing an uninitialized > pointer. Thanks, already fixed by adding app=(struct Server_class *) calloc(1, sizeof(struct Server_class)); |
|
#5
|
| On Sep 30, 11:20*pm, eotcl > > You have declared app as a pointer, but haven't pointed it to > > anything. > > Thus the dereference * app->dpy *is dereferencing an uninitialized > > pointer. > > Thanks, already fixed by adding > > * app=(struct Server_class *) calloc(1, sizeof(struct Server_class)); Don't cast the result of malloc, calloc, or realloc. Thye cast will hide the compiler's warning message if you happen to omit the #include of stdlib.h. A better way: app = calloc( 1, sizeof (*app) ); -- Fred Kleinschmidt |