收集了一下C语言中的crash,到底会有多少种死法? 欢迎大家来补充
最简单开始,没有初始化
#include <stdio.h>
int main()
{
int *p;
*p = 1;
}
访问数组越界
#include <stdio.h>
int main()
{
int a[5];
printf("%d\n", a[10]); //这里一般还没到越界的地方呢
printf("%d\n", a[10000]); //不过这里就够呛了,哈哈
return 0;
}
用char *p声明的存在了一个特殊的地方,叫静态或者只写区间? 反正要crash
#include <stdio.h>
int main()
{
char a[10] = "abcdefg";//这个在栈上,可写
a[1]='x';
printf("%s\n",a);
char *str = "abcdefg";//这个不可写
printf("%s\n",str);
printf("%c\n",str[1]);
str[1] = 'd'; // 开始crash
return 0;
}
一旦堆上的内存被释放了一把,你再去访问会导致crash? 我只能说有可能
一次申请,两次释放?百分百crash
#include <stdio.h>
int main(void)
{
char *p = malloc(3);
printf("1%c\n",p[0]);
printf("1%c\n",p[0]);
*p = 'a';
printf("2%c\n",p[0]);
printf("2%c\n",p[0]);
free(p);
printf("3%c\n",p[0]);//内容被释放了
printf("3%c\n",*p);
printf("3%c\n",p[0]);
*p = 'b'; //释放后再写,似乎没有crash!
printf("4%c\n",p[0]);
printf("4%c\n",*p);
printf("4%c\n",p[0]);
free(p); //第二次释放
return 0;
}
1
1
2a
2a
3
3
3
4b
4b
4b
*** glibc detected *** ./aa: double free or corruption (fasttop): 0x09b58008 ***
make: *** [print] Segmentation fault (core dumped)
这是个有趣的例子,反复调用main导致栈用完了
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
main();
}
这个例子如果运行在大内存或者有虚拟内存机制的地方,一般出不了问题
int main()
{
unsigned int i = 0;
for(i=0; i< 0xFFFFFFFF;i++);
char *p = malloc(100000);
return 0;
}
下面这个例子最有意思了,变量只能够访问一次,第二次就不见了,因为访问的是栈上的内容,一旦func结束后内容就不可靠了
#include <stdio.h>
char* func()
{
char c = 'a';
return &c; //return tmp value address, the value is tone in stack
}
int main(int argc, char *argv[])
{
char *ptr = func();
printf("1%c\n",ptr[0]); //first print still right
printf("1%c\n",ptr[0]); //disappear now, strange
printf("2%c\n",*ptr);
printf("2%c\n",*ptr);
ptr[0]='b';
printf("3%c\n",*ptr);
printf("3%c\n",*ptr);
printf("4%c\n",ptr[0]);
printf("4%c\n",ptr[0]);
char d = 'd';
char *dp = &d;
dp[0]='e';
printf("5%c\n",*dp);
printf("5%c\n",*dp);
printf("6%c\n",dp[0]);
printf("6%c\n",dp[0]);
return 0;
}
1a
1
2
2
3b
3
4
4
5e
5e
6e
6e
gcc --version
gcc (GCC) 4.4.5 20110214 (Red Hat 4.4.5-6)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.