Skip to main content
Tweeted twitter.com/StackCodeReview/status/684920780614942720
edited title
Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Detecting arithmetic overflow in C with nasmNASM

edited tags
Link
200_success
  • 145.6k
  • 22
  • 191
  • 481
Source Link
coderodde
  • 32.1k
  • 15
  • 78
  • 205

Detecting arithmetic overflow in C with nasm

This snippet is about detecting whether the carry flag is set or cleared. I work on Mac OSX, so my snippet supports Mac only.

First, we need a routine that does the job:

func.s:

global _read_carry_flag

_read_carry_flag:
    mov al, 0
    jnc end 
    mov al, 1
end:
    ret

(Try nasm2 -f macho64 func.s for compiling into an object file.)

main.c:

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#define A (2 * 1000 * 1000 * 1000)
#define B (1 * 1000 * 1000 * 1000)

extern bool read_carry_flag();

int main(int argc, char* argv[])
{
    int32_t a = A;
    int32_t b = B;
    int32_t ret = a + a + b;

    printf("%d\n", read_carry_flag());

    a = A;
    b = 1;
    ret = a + b;

    printf("%d\n", read_carry_flag());
    return 0;
}

(Try gcc -o prog main.c func.o for obtaining a process image.)

I would like to hear about possible improvements/extensions to the idea.