Segmentation Fault in C Function Printing Double from Assembly Code

I'm encountering a segmentation fault while calling a C function from assembly code to print floating point values. The C function employs a switch statement to handle different data types, including doubles.
Been able to confirm that the issue lies within the printf function when handling double values, as converting the double to an integer before printing works correctly. But directly printing the double using %f results in a segmentation fault.
I'm running this on a 64 bit system (Ubuntu 22.04) and the GCC compiler.

Any insights into resolving this issue ?
file0.jpg
file1.jpg
Solution
@Marvee Amasi It sounds like you’re dealing with an alignment issue or possibly an issue with how the double is being accessed in memory. When you cast a long to a double, there’s a chance that the address isn’t properly aligned for accessing double-precision floating point numbers, especially on a 64-bit system.

A quick test would be to ensure that val is aligned correctly before casting it to a double. You can add an assertion to check the alignment

case 6:
  assert(val % sizeof(double) == 0);  // Ensure alignment
  c = *(double*) val;
  printf("%f\n", c); /* seg fault */
  break;

If the assertion fails, then the address val isn’t properly aligned for a double, which would cause the segmentation fault.

Also, consider checking how the value of val is being passed from the assembly code. If there's any chance that it’s being misaligned before it’s passed to the C function.
Was this page helpful?