Thus Spake Rama

A small attempt at blogging!! I will mostly be writing down funny incidents in my life and travels.

Sunday, November 22, 2009

Code aborting due to unhandled instruction error

The standard string class defined in string.h must not be used inside printf family of functions (eg fprintf, sprintf). If you do, the compiler will warn you as shown below. At runtime, the call aborts with a possible error message being "Program received signal SIGILL, Illegal instruction". Unless you look at the warnings, you wont know why the error is coming. This post is meant to help you save some trouble in such cases.

Code snippet from strings.C

Line 100: string str = "my string";
Line 101: fprintf (stderr, "%s :: No category implemented for this keyword\n", str);

$>g++ strings.C
strings.C:101: warning: cannot pass objects of non-POD type ‘const struct std::basic_string, std::allocator >’ through ‘...’; call will abort at runtime
strings.C:101: warning: format ‘%s’ expects type ‘char*’, but argument 3 has type ‘int’

Sure enough, When you run a.out, the execution aborts, but with an obscure error msg as shown below.

$>./a.out
Illegal instruction

If you run valgrind, you will get error message that would look like:

vex x86->IR: unhandled instruction bytes: 0xF 0xB 0x55 0x89
valgrind: Unrecognised instruction at address 0x405aea9.

Process terminating with default action of signal 4 (SIGILL)
Illegal opcode at address 0x405AEA9

Solution: The solution is to replace "str" as third argument of fprintf with str.c_str()!!
Compiling and running the code will give print the following o/p
my string :: No category implemented for this keyword.

Note that the compilation warning will not exist anymore.

Moral: If code aborts due to obscure error msg, look at your compiler warnings!

As usaul, any questions/clarifications, post them in comments section and I will answer them.

--rags

Labels: , , , ,

0 Comments:

Post a Comment

<< Home