Get offset


1 #include <stdio.h>
2
3 struct foo {
4     char a;
5     char b[10];
6     char c;
7 };
8
9 int main()
10 {
11
12
13     printf("offsetof is %d\n", &(((struct foo*)0)->a));
14     printf("offsetof is %d\n", &(((struct foo*)0)->b));
15     printf("offsetof is %d\n", &(((struct foo*)0)->c));
16 }

Result:

offsetof is 0
offsetof is 1
offsetof is 11

More details on:

http://en.wikipedia.org/wiki/Offsetof

Get offset

Pitfall about free function

1. Still can access the pointer after free the memory.


#include <stdlib.h>
#include <stdio.h>

int main()
{
char *buf;
buf = (char *)malloc(sizeof(char));
*buf = 'a';
free(buf);

if (buf)
{
printf("buf is not NULL\n");
printf("buf %c\n", *buf);
}
else
printf("buf is NULL\n");

return 0;
}

<section>