1, 简单的小示例代码
按理说 malloc 的size 是 1024*128,这里却需要 1024*132才能及时触发 segmentation fault
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1024*131
int main()
{
char *p = 0;
p = malloc(SIZE);
p[SIZE -1] = 'a';
free(p);
printf("p = %c\n", p[SIZE - 1]);
p[SIZE-1] = 'b';
printf("p = %c\n", p[SIZE -1]);
return 0;
}
运行效果:
2,示例2
改成 1024*132
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1024*132
int main()
{
char *p = 0;
p = malloc(SIZE);
p[SIZE -1] = 'a';
free(p);
printf("p = %c\n", p[SIZE - 1]);
p[SIZE-1] = 'b';
printf("p = %c\n", p[SIZE -1]);
return 0;
}
编译运行:
待解。。。
3, 结构体对齐
原则:按照sizeof 从小到大排序定义结构体成员,会比较节省空间
示例代码:
#include <stdio.h>
struct aaaa{
char a;
int b;
short c;
char d;
};
struct bbbb{
int b;
char a;
short c;
char d;
};
struct cccc{
int b;
short c;
char a;
char d;
};
int main()
{
printf("sizeof(aaaa) = %ld\n", sizeof(struct aaaa));
printf("sizeof(bbbb) = %ld\n", sizeof(struct bbbb));
printf("sizeof(cccc) = %ld\n", sizeof(struct cccc));
return 0;
}
编译运行: