Re: Seg Fault: Debugging Beginner

On Sun, 2003-12-21 at 05:19, Sukrit K Mehra wrote:
Thanks all for helping me throughout the last two weeks. 
I have a code snippet that compiles prefectly but the app then gives a 
segmentation fault on running. Same code snippet elsewhere in the application 
works alright.
How can I correct it? What do seg fault generally mean?

A seg fault occurs when you access memory that you don't have permission
to access.  This is a common C problem, as C requires that you allocate
and manage your own memory.

To find the place in your code where it is segfaulting, compile your
program with a "-g" (both compile and link stage) parameter.  Then use a
debugger like ddd or kdbg (comes with KDE), or even commandline gdb and
you can see the exact line of code where the problem is occurring.  You
can also use a debugger to step through your code to watch variables and
make sure they are right.  Debuggers seem to be lost arts these days,
but I assure you learning a powerful debugging interface like ddd is
well worth your time.

To fix a seg fault, you need to make sure you're not accessing memory
beyond the end of an array, or that your pointer isn't NULL.  Also you
need to make sure that your pointer is pointing into valid memory.


The code is given below.

void display_db(void) {
      int i, j;
    gint row_status = -1;
    gchar *text[3];
    PGresult *res;
    PGconn *conn;
    conn = PQconnectdb(CONSTRING);
    if(PQstatus(conn) == CONNECTION_BAD){
      fprintf(stderr, "Connection to database failed.\n");
        fprintf(stderr, "%s", PQerrorMessage(conn));

      gtk_clist_clear(GTK_CLIST(lookup_widget (GTK_WIDGET(window1), "clist1")));
    gtk_clist_freeze(GTK_CLIST(lookup_widget (GTK_WIDGET(window1), 
      for(i = 0; i < PQntuples(res); i++) {
              for(j=0; j <PQnfields(res); j++) {
            text[j] = PQgetvalue(res, i, j);
          row_status = gtk_clist_append(GTK_CLIST(lookup_widget 
(GTK_WIDGET(window1), "clist1")), text);
    gtk_clist_thaw(GTK_CLIST(lookup_widget (GTK_WIDGET(window1), "clist1")));
Michael Torrie <torriem byu edu>

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]