ravelinx ravelinx - 16 days ago 5
C Question

C inline Assembly generating unhandled exception

So I have this function written in C

int transform ( char * p )
{
if(*p!='-'){
return 0;
}

p++;
if(*p == 'a')
{
return 1;
}
else if(*p == 'b')
{
return 2;
}
else
{
return 0;
}
}


And I tried to translate it to inline assembly ia32 like this

int trasform ( char * p )
{
int result;
_asm
{
mov eax, p
mov ebx, 0
mov bl, [eax]
cmp bl, '-' ;
jne invalid
mov bl, [4*eax]
cmp bl, 'a'
jne isB
mov result, 1
mov eax, result
jmp out
isB:
cmp bl, 'b'
jne invalid
mov result, 2
mov eax, result
jmp out
invalid:
mov result, 0
mov eax, result
out: ; end

}
return result;
}


When I have the function written in C it works perfectly in Visual Studio, but when I change it to inline assembly and execute the code, I get an Error saying


Unhandled exception at 0x774e15ee in proyect.exe : 0xC0000005: Access violation reading location 0x01745388.


Does this problem has to be with the code or is it problem of visual studio?

I debugged my code and found that error is in this line

mov bl, [4*eax]

Answer

As the debugger indicates, the problem is in this instruction:

mov bl, [4*eax]

Looking at the C code, its intention is to load the second byte of the string into bl. The pointer to the first byte is eax, so the pointer to the second byte is eax+1. That is, the proper command is

mov bl, [eax+1]

Alternatively, you could do that with two instructions:

inc eax
mov bl, [eax]

This is more in line with C code:

p++;
if (*p == ...)

but does the same.