aliask
aliask

Reputation: 133

snprintf crash when displaying %d or %u

I'm trying to print an integer into a string with snprintf for display on an OLED display from an ARM micro. However, when I use %d or %u the micro locks up and stops executing. Using %x or %c works fine, but the output isn't much use.

What could cause this behaviour? Unfortunately I don't have access to a JTAG device to debug. I'm using arm-none-eabi-gcc to compile and it's all running on a maple mini.

UPDATE

Passing values < 10 seems to make it work.

Upvotes: 3

Views: 3161

Answers (4)

aliask
aliask

Reputation: 133

This actually turned out to be a stack size issue with the RTOS that I was using. I guess the added complexity of the snprintf call was pushing it over the limit and crashing.

Thanks to all who took a crack at answering this!

Upvotes: 2

Igor Skochinsky
Igor Skochinsky

Reputation: 25308

Passing values < 10 seems to make it work.

This sounds to me as if you have a missing/non-working divide routine. printf/sprintf usually prints decimal numbers by successively dividing them by 10. For numbers less than 10 the division is not necessary and that's probably why it doesn't work.

To check, make a function which divides two variables (dividing by a constant is usually optimized into multiplication by the compiler). E.g.:

int t()
{
  volatile int a, b; // use volatile to prevent compiler optimizations
  a = 123;
  b = 10;
  return a/b;
};

Also, check your build log for link warnings.

Upvotes: 1

wildplasser
wildplasser

Reputation: 44250

Do you have a prototype in scope ? snprintf() is a varargs function, and calling a varargs may involve some trickery to get the arguments at the place where the function expects them.

Also: always use the proper types when calling a varargs function. (the one after the '%' is the type that snprintf() expects to find somewhere, 'somewhere' may even depend on the type. Anything goes...) in your case : "%X" expects an unsigned int. Give it to her, either by casting the parameter in the function call, or by using "unsigned int sweeplow;" when defining it. Negative frequencies or counts make no sense anyway.

Upvotes: 0

Dietrich Epp
Dietrich Epp

Reputation: 213508

It can't be a type error since %x and %u both specify the same types. So it has to be a problem in snprintf itself. The only major difference between the two is that %u has to divide integers and compute the remainder, whereas %x can get by with shifts and masks.

It is possible that your C library was compiled for a different variety of ARM processor than you are using, and perhaps it is using an illegal instruction to compute a quotient or remainder.

Make sure you are compiling your library for Cortex M3. E.g.,

gcc -mcpu=cortex-m3 ...

Upvotes: 0

Related Questions