Skip to content

Instantly share code, notes, and snippets.

@SteveLauC
Last active March 17, 2022 03:34
Show Gist options
  • Save SteveLauC/1beb36ea0f2509f6fbb8d521493b7efa to your computer and use it in GitHub Desktop.
Save SteveLauC/1beb36ea0f2509f6fbb8d521493b7efa to your computer and use it in GitHub Desktop.
Interget overflow check program
/*
* signed int addition overflow test
* exit(EXIT_FAILURE) if result overflows
* print the correct value if everything is good.
*/
#include <stdio.h>
#include <stdlib.h>
int add(int x, int y) {
int result = x + y;
if ((x > 0 && y > 0 && result < 0) || (x < 0 && y < 0 && result > 0)) {
printf("addition overflow\n");
printf("%d\n", result);
exit(EXIT_FAILURE);
}
return result;
}
int main() {
// overflow case
int x = 2147483647;
int y = 1;
printf("%u\n", add(x, y));
return 0;
}
/*
* signed int subtraction overflow test
* exit(EXIT_FAILURE) if result overflows
* print the correct value if everything is good.
*/
#include <stdio.h>
#include <stdlib.h>
int sub(int x, int y) {
int result = x - y;
if ((x>0&&y<0&&result<0)||(x<0&&y>0&&result>0)) {
printf("subtraction overflow\n");
printf("%d\n", result);
exit(EXIT_FAILURE);
}
return result;
}
int main() {
// overflow case
int x = 2147483647 ;
int y = -1;
printf("%d", sub(x, y));
return 0;
}
/*
* unsigned int addition overflow test
* exit(EXIT_FAILURE) if result overflows
* print the correct value if everything is good.
*/
#include <stdio.h>
#include <stdlib.h>
unsigned int add(unsigned int x, unsigned int y) {
unsigned int result = x + y;
if (result < x && result < y) {
printf("addition overflow\n");
printf("%u\n", result);
exit(EXIT_FAILURE);
}
return result;
}
int main() {
// overflow case
unsigned int x = 4294967295u;
unsigned int y = 1u;
printf("%u\n", add(x, y));
return 0;
}
/*
* unsigned int subtraction overflow test
* exit(EXIT_FAILURE) if result overflows
* print the correct value if everything is good.
*/
#include <stdio.h>
#include <stdlib.h>
unsigned int sub(unsigned int x, unsigned int y) {
unsigned int result = x - y;
if (result > x && result > y) {
printf("subtraction overflow\n");
printf("%u\n", result);
exit(EXIT_FAILURE);
}
return result;
}
int main() {
// overflow case
unsigned int x = 1u;
unsigned int y = 2u;
printf("%u", sub(x, y));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment