I'm having trouble solving a school exercise , I'm supposed to change a char array in c using inline assembly. In this case change "ahoy" to "aXoy", but I'm getting segmentation fault. This is my code:
#include <stdio.h>
int main() {
char string[] = "ahoy";
__asm__ volatile (
"mov %0, %%eax;"
"movb $'X', 1(%%eax);"
: "=m"(string) : "0"(string) : "memory", "eax");
printf("%s\n", string);
return 0
}
with this: "mov %0, %%eax;" I'm trying to store address of the array in register
then with this: "movb $'X', 1(%%eax);" I want to store byte 'X' in location pointed to by (%%eax) offset by 1 byte(char),
I have string both as output and input, and "memory","eax" in clobber since I'm modifying both. What is wrong with my code?
stringas input AND output then mark it as"+m"instead of"=m"and then drop the"0"(string)altogether. This linemov %0, %%eax;will move the 32-bit value AT the memory address to EAX since %0 is a memory operand. You want to put the ADDRESS of %0 in EAX it appears. Uselea %0, %%eax;instead ofmov %0, %%eax;- Michael Petchstring) will fault since the stack address can't be represented properly in a 32-bit value. Make sure you compile this with-m32or modify the code to use a 64-bit register for the address (RAX instead of EAX) - Michael Petch__asm__ volatile ( "lea %0, %%eax;" "movb $'X', 1(%%eax);" : "+m"(string) :: "memory", "eax");- Michael Petch+modifier has been around for almost forever. They are all documented here: gcc.gnu.org/onlinedocs/gcc/Modifiers.html#Modifiers - Michael Petch+myou don't need to use thememoryclobber since the compiler will realize all of thestringin memory first since you are using anmconstraint. Alternatively you could have done__asm__ volatile ( "movb $'X', 1(%0);" :: "r"(string) : "memory");. Memory clobber would be needed since in this case you are passing the address ofstringthrough a register and not a memory operand. - Michael Petch