Domanda

I'm getting segfault error in writeLogs routine.

(gdb) print *analyzers->analyzer2.log
Cannot access memory at address 0x80000007f5b4
(gdb) print analyzers->analyzer2.log
$13 = (int *) 0x80000007f5b4

So, the pointer seems to exist, the value, not. I would expect, I have same pointer and same value in every routine, which I call. See the attached code:

typedef struct analyzer_t
{     
  int *log;
}analyzer_t;


typedef struct analyzers_t
{
  analyzer_t analyzer2;
}analyzers_t;



int MarketTalkMessagesVerarbeiten(unsigned char *datap, size_t size, GTree* t, analyzers_t *analyzers)
{
    *analyzers->analyzer2.log++;
}
int writeLogs(char *name, analyzers_t *analyzers)
{
   printf("Anal: %d\n", *analyzers->analyzer2.log );  
}
gboolean main_loop(mainloop_param_t *data)
{
   analyzers_t *analyzers = data->analyzers;
   MarketTalkMessagesVerarbeiten(pUncompressStreamData, sizeBMB, t, analyzers);
   writeLogs(namelist[i]->d_name,  analyzers);
}
int main()
{
  int log_a2                = 0;
  analyzers_t analyzers;
  analyzers.analyzer2.log   = &log_a2;
  mainloop_param_t mlparams;
  mlparams.analyzers = &analyzers;
  GMainLoop* loop = g_main_loop_new (NULL, FALSE);

  g_timeout_add (5000, (GSourceFunc)main_loop, &mlparams);
  g_main_loop_run (loop);

}
È stato utile?

Soluzione

++ binds tighter than *.

So

  *analyzers->analyzer2.log++;
  1. Increments ...log (a pointer!)
  2. Dereferences the result of 1 (which most probably points to invalid memory and with dereferencing it therefore invokes undefined behaviour and with this the observed crash)

To increment where ...log points to, do:

(*analyzers->analyzer2.log)++;

That is:

  1. Dereference analyzers->analyzer2.log
  2. Increment to what step 1 points to
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top