Use format specifiers to print output values
What you should not do
#include<limits.h>
#include<stdio.h>
void main(){
unsigned long foo = ULONG_MAX;
printf(foo);
}
When the above program is run with or without the "-Wformat-security" command line option, a warning is given by the compiler. The warning is "warning: format not a string literal and no format arguments [-Wformat-security]". This cause the program to crash. When the above C program is run, the output is "Segmentation fault (core dumped)".
What you should do
#include<limits.h>
#include<stdio.h>
void main(){
unsigned long foo = ULONG_MAX;
printf("%lu", foo);
}
The above program when run would print the value, 18446744073709551615 which is maximum value of unsigned long integer.
Concept Map
This maps to E in the Concept Map.
Use compiler command line arguments to warn about incorrect results when unsigned and signed integers are compared
In the program below a signed and an unsigned integer are compared.
#include<stdio.h>
bool foo (int x, int unsigned y)
{
printf("%u\n", y);
printf("%x\n", y);
if (x<=y){
return true;
}
return false;
}
void main(){
bool res = foo(4,-5);
printf("%s\n", res ? "true" : "false");
}
What you should not do
When the above program is compiled without the -Wsign-compare option, no warning is given about the comparison of an unsigned integer, y and signed integer x.
What you should do
-Wsign-compare option gives a warning about the comparison of an unsigned integer, y and signed integer x. The warning is, "comparison between signed and unsigned integer expressions [-Wsign-compare]"
The following should be done to compile a program in gcc compiler using the -Wsign-compare flag.
gcc -Wsign-compare -o greaterThan greaterThan.c
Concept Map
This maps to E in the Concept Map.