Thursday, February 5, 2009

Traps in printf

I was debugging this segmentation fault that we were seeing at a customer. It wasn't caught because in never hit the code path in dev/QA. It would happen when logging was enabled. GNU debugger seemed to indicate that the logging library was using the vnsprintf call which uses va_list (variable argument list) as input. I spent close to 2 hrs trying to debug this before realizing the error. So lets see if you can try to figure it out. The same problem exists in printf as well:

printf(" some randmon long %l and string %s \n", 4, "hello");

compile the above and it will throw segv.

Thing is, its easy to assume that %l is a specifier for long. Its not. Its a length specifier not type specifier. You have use %ld. In absense of that printf will assumen that the first arguement ( 4) is a string and throw segv.

Lesson: variable arugement is very powerful. but be aware of the traps.

No comments:

Post a Comment