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 ?
attachment 0
attachment 1
4 Replies
Marvee Amasi
Marvee Amasi2mo ago
From my_call.asm, %r12 points to memory allocated in the heap. The weird thing is that when I convert the double to an integer before calling printf , there is no segmentation fault by uncommenting the line in case 6 and commenting the line below , it comes out with the right result that is 5 . During debugging, I found the segmentation fault occured within the subroutines of the printf function where I can't see the code. Also even if I define a random double, I can't print it
RED HAT
RED HAT2mo ago
@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;
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.
Marvee Amasi
Marvee Amasi3d ago
Thanks this was helpful man
Want results from more Discord servers?
Add your server