Skip to content

Instantly share code, notes, and snippets.

@ichaos
Last active December 18, 2015 00:19
Show Gist options
  • Save ichaos/5695877 to your computer and use it in GitHub Desktop.
Save ichaos/5695877 to your computer and use it in GitHub Desktop.
subtle and funny c code
/**
* Array is different with pointer, although it is used like a pointer.
* Here is an example
*/
#include <stdio.h>
int main() {
int a[5];
printf("%p\n", a);
printf("%p\n", a + 1);
printf("%p\n", &a);
printf("%p\n", &a + 1);
return 0;
}
/*
* shortest crash C program
* The program will try to execute main as if it were a function
* and this does not work because the compiler has placed it in the data segment,
* which is not executable. So it does actually not matter what the variable main is initialized to.
* From here: http://llbit.se/?p=1744&utm_source=Coder+Weekly&utm_campaign=ac08a43175-Coder_Weekly_63&utm_medium=email&utm_term=0_3b843cbb69-ac08a43175-24562857
* Also: https://news.ycombinator.com/item?id=5762262
*/
int main;
/*
When a C program is compiled, the compiler creates one or more object files with symbolic references to libraries and global objects (functions and variables). The object files are then linked – symbolic references replaced by addresses – to create an executable.
The compiler provides an entry point that calls main in one of the object files. Calling main means that we try to execute the instructions at the address stored at the location main was linked to.
Interestingly, the linker has no concept of the types of different objects – it only knows of their addresses. So, if we replace main by a regular global variable, the compiler will happily build the object file because it does not care what type of object main is, and the linker will happily link it because it is only concerned with the address of main.
*/
/**
* use typedef to define a array symbol
*/
struct A {
int a;
int b;
};
typedef struct A aa[1];
int main() {
struct A a = { .b = 1, .a = 2 };
//aa b is syntactic sugar, which is same with struct A b[1], like int x[1]
aa b = { a };
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment