Those errors might be surprising and a good exercise for C beginners:
Empty printf
#include <stdio.h>
int main()
{
printf("");
return 0;
}
error: zero-length gnu_printf format string
Macros
#include <stdio.h>
#define MY_MACRO printf("Hello World\n");
int main()
{
if (1)
MY_MACRO;
else
printf("Crazy, huh?\n");
return 0;
}
macro.c: In function ‘main’:
macro.c:8: error: ‘else’ without a previous ‘if’
Single and Double quotes
#include <stdio.h>
int main()
{
printf('hello, world\n');
return 0;
}
macro.c:5:9: warning: character constant too long for its type
macro.c: In function ‘main’:
macro.c:5: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast
/usr/include/stdio.h:339: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
macro.c:5: warning: format not a string literal and no format arguments
Thanks to drpaulcarter.com for this example:
int main()
{
const char * myPointer = 'A';
(void) myPointer;
return 0;
}
macro.c: In function ‘main’:
macro.c:3: warning: initialization makes pointer from integer without a cast
Pointers
#include <string.h>
int main()
{
char * myPointer;
strcpy(myPointer, "Hello World!");
return 0;
}
macro.c: In function ‘main’:
macro.c:7: warning: ‘myPointer’ is used uninitialized in this function
Loops
int main()
{
int x = 42;
while( x > 0 );
x--;
return 0;
}
No compiler error, but an infinite loop.
Null terminator of Strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char myArray[20];
printf("Characters: %i\n", strlen(myArray));
strcpy(myArray, "abc");
printf("Characters: %i\n", strlen(myArray));
strcpy(myArray, "Hello World!");
printf("Characters: %i\n", strlen(myArray));
printf("String: -%s-\n", myArray);
printf("Size: %i Byte\n\n", sizeof(myArray));
char * myString = malloc(strlen(myArray));
strcpy(myString, myArray);
printf("String: -%s-\n", myString);
printf("Size: %i Byte\n", sizeof(myString));
printf("Characters: %i\n\n", strlen(myString));
char * breakIt = malloc(strlen(myString));
strcpy(breakIt, myString);
printf("String: -%s-\n", breakIt);
printf("Size: %i Byte\n", sizeof(breakIt));
printf("Characters: %i\n", strlen(breakIt));
return 0;
}
Again, you don't get a compiler error, but some strange results:
Characters: 0
Characters: 3
Characters: 12
String: -Hello World!-
Size: 20 Byte
String: -Hello World!-
Size: 4 Byte
Characters: 12
String: -Hello World!-
Size: 4 Byte
Characters: 13