how do i move the value of %eax to the memory location of %0

int size 10;
long *list = (long*) malloc(size*sizeof(long));
asm(
movl   $999, %%eax
movl   %eax, (%0) // this is what im trying, how do i fix it?
:"=r"(list)
:"0"(list), "a"(strLen)
);

Dani AI

Generated

Short answer: let the compiler provide the memory operand or the pointer register with the correct constraint, and tell the compiler about the memory side-effect. The usual patterns are either a memory output operand (=m) or pass the pointer as a register (r) and dereference it in the template. Avoid mixing operand placeholders and explicit register names incorrectly (that causes the assembler/operand-substitution confusion seen in the original post).

Example — write a 32-bit value into *list using a memory output operand:

int value = 999;
asm volatile (
  "movl %1, %0"
  : "=m" (*list)
  : "r" (value)
  : "memory"
);

Example — pass the pointer in a register and store via (%0):

int value = 999;
asm volatile (
  "movl %1, (%0)"
  :
  : "r" (list), "r" (value)
  : "memory"
);

Notes and gotchas:

  • Use matching operand widths: movl for 32-bit, movq for 64-bit. On x86_64 long is 8 bytes; on 32-bit it is 4 bytes. Prefer fixed-width types (int32_t/int64_t) when mixing asm and C.
  • If you use an explicit register name inside the template (e.g., %%eax), either list the register as a constraint (so compiler knows you need it) or add it to the clobber list. Using operand placeholders (%0, %1) is less error-prone.
  • Always use the "memory" clobber when the asm writes memory that the compiler might optimize around, or use explicit memory output operands so the compiler understands the effect.
  • Inline asm is brittle; prefer *list = value; in C unless assembly is required.

This answer expands on 's working example and 's 32/64-bit pointer note by showing the more robust =m and r patterns. For details and more examples of GCC extended asm syntax and constraints, see the GCC documentation: GCC Inline Assembly.

Recommended Answers

All 4 Replies

Try something like below

#include <stdio.h>
#include <stdlib.h>

unsigned long *lptr = NULL;

int main()
{
  lptr = (unsigned long*)malloc(sizeof(unsigned long));
  
  /*check if allocation failed*/
  
  __asm__ 	(
				"movq	%0, %%rax\n\t"
				"movq	$6, (%%rax)\n\t"
				:"=m"(lptr)
			);
			
  fprintf(stdout, "ans->%lu\n", *lptr);
  return 0;
}
commented: =D great helpl +2

yah..=D that works for me..
and a other question.. if my system is 32bit, i coulnt use 64bit registers?

yah..=D that works for me..
and a other question.. if my system is 32bit, i coulnt use 64bit registers?

Then just replace "%%rax" with "%%eax" and "movq" with "movl"

commented: :D thx +2

ya. thx for all your helo :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.