The value of the change in function C upon return. Damaged stack?

Today I have a very strange problem. In short, my function returns one value, the caller gets a different value. Somewhere next to my code I call:

Message* m = NULL; m = connection_receive(c); 

Where connection_receive is defined as follows:

 Message* connection_receive(Connection* c) { Message* k; if (c->state == CON_STATE_AUTHENTICATED) { pthread_mutex_lock(&c->mutex_in); if (g_queue_is_empty(c->in)) k = NULL; else k = (Message*)g_queue_pop_head(c->in); pthread_mutex_unlock(&c->mutex_in); /* Until here, k is reachable and contains the correct data. */ return k; } else return NULL; } 

Gdb runs here, I stopped right before returning and right after the assignment:

 222 return k; (gdb) pk $1 = (Message *) 0x7ffff0000950 (gdb) n 226 } (gdb) n main () at src/main.c:57 57 if (m) (gdb) pm $2 = (Message *) 0xfffffffff0000950 

Of course, if we try to access 0xfffffffff0000950, we get a segmentation error.

If I change the function and instead of returning the value, use the second parameter to pass the value that it works, but I would like to know what went wrong on that.

Many thanks.

EDIT: It works, but it is not convenient. And I would also like to know why such a strange error occurs.

 void connection_receive2(Connection* c, Message** m) { if (c->state == CON_STATE_AUTHENTICATED) { pthread_mutex_lock(&c->mutex_in); if (g_queue_is_empty(c->in)) *m = NULL; else *m = (Message*)g_queue_pop_head(c->in); pthread_mutex_unlock(&c->mutex_in); } else *m = NULL; } 

EDIT2: Solvable. Thanks to everyone. The problem was a typo in the header file. I cannot use -Werror because I need to do something to raise some warnings, and in the big make release and big header I skipped it.

+7
source share
3 answers
  • How is your m determined?
  • Does your caller have access to the correct prototype?
  • What architecture do you work in?

I suspect that there is a mismatch with types, and that my question 2 is the essence of all.

You are returning a pointer with (I suppose so) 48 or 64 bits. The caller, however, is thinking of getting an int , which may contain 32 bits and is signed. When converted back to a pointer, the value gets an extended character.

+5
source

Did you click the malloc: ed object in the queue? If not, and instead pop the stack object, then when you may encounter strange behavior when you place the elements.

0
source

We faced the same problem, and the main reason was the implicit declaration of the connection_receive () function. Thus, it was defaulted to default, which was signed and then saved to m.

0
source

All Articles