简体   繁体   中英

Segmentation Fault using C macros

I have a curious issue while working with a slighty modified MobileC build.

I get a segmentation fault in a macro but when i put printfs in the code (its not possible to debug otherwise since it's interpeted C) I can't get the exact point where it happens.

This is the code:

...
printf("just to check there is no problem accessing "node" %d\n", node);\
printf("this will be printed\n"); \
node_type##_Destroy(node); \
printf("this will not be printed\n"); \
...

And the code of Destroy is the following:

int name##_Destroy( name##_p name ) \
{ \
printf("this will not be printed\n");    \
...

I have not modified this part of the code (except for the printfs ) so I guess it's ok. Do you have any idea what can be happening here?

There are two red flags in this code, but you haven't really shown us enough.

printf("just to check there is no problem accessing "node" %d\n", node);\
printf("this will be printed\n"); \
node_type##_Destroy(node); \
printf("this will not be printed\n"); \

This is clearly a macro, but it's a multi-statement macro. This is the easiest way to screw up with macros, because it can be called like this:

#define MACRO() puts("A"); puts("B")
// prints "B"
if (0) MACRO();

Secondly, that string constant is very suspicious:

"just to check there is no problem accessing "node" %d\n", node

Notice how node is purportedly an int , but it appears between two string constants without a compilation error. An int shouldn't be able to do that, so node is probably not quite an int . It might be an entire expression, who knows?

Segfault on delete almost always points to a corrupted heap. Something has trashed the heap where your pointer lives (or where it is keeping track of prev/next pointers) and causing a jump to hyperspace. Managed code makes this less likely, but it is still where I would start.

Thank you for your answers. Now I know what happened.

Dietrich Epp, indeed node wasn't an int (I just wanted to know whether there was a problem accessing it since I was screwed up by the error and didn't have a clue about what was happening). Thank you for warning me about C Macros. I've read a bit about and finally I've figured out what was happening.

node_type type was agent . Therefore the macro expanded to agent_Destroy(node). The issue was that in Mobile C code there was a function than was named agent_Destroy(agent_p agent). What happened was that both functions executed and the first one was the one defined directly in the code where there was a segmentation fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM