Search code examples
assemblycontrol-flowinstructions

Testing for 0 after gets


Hey I have a snippet of assembly code that does not make sense to me

.text:004016C5 prompt_uid:             ; "[ User %d    ]\t"
.text:004016C5 mov     [esp+0Ch+var_C], offset aUserD
.text:004016CC mov     ecx, [ebp+arg_0]
.text:004016CF mov     [esp+0Ch+var_8], ecx
.text:004016D3 call    printf
.text:004016D8 mov     [esp+0Ch+var_C], esi
.text:004016DB call    gets
.text:004016E0 test    eax, eax        ; test eax=0
.text:004016E2 jz      short prompt_uid

At first I was confused by the test eax,eax and jz following a gets.

"Why would any input be 0?". Then I thought "Ok. strings are terminated by a nullbyte so an empty string should result in the test setting ZF"

But when I tested it in practice the jz was never taken. Even when I just hit enter at the prompt.

Where is my mistake?


Solution

  • The gets() reference gives the answer to when it will return NULL;

    RETURN VALUE

    Upon successful completion, gets() shall return s. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and gets() shall return a null pointer. If a read error occurs, the error indicator for the stream shall be set, gets() shall return a null pointer, [CX] and set errno to indicate the error.

    In other words, gets() may return NULL on end of file or a read error, not in normal "press return" operation.