linux C++服务在编写与运行过程中,难以避免会出现各种各种的崩溃,特在此收集常见多引起程序产生coredump的各种情形,具体例子还在不断地总结与收集中。
1.stackoverflow问题;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[1];
buf[1]=1;
//strcpy(buf,"111111111");
printf("buf is %p:%s\n",buf,buf);
return 0;
}
运行结果是:
*-buf is 0x7ffd955dcfc7:
* stack smashing detected *: ./test1 terminated
已放弃 (核心已转储)*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class Node
{
public:
int a;
int b;
int c;
//int getNum(){return c;}
};
int main()
{
char buf[2];
Node* p = (Node*)buf;
printf("buf is %p\n",p);
int a=p->a;
int b=p->b;
p->a=0;
p->b=0;
p->c=0;
return 0;
}
buf is 0x7fff2b2f27b0
* stack smashing detected *: ./test1 terminated
*这里如果char buf = new char[2];程序运行没有崩溃;但是这不代表这样写没问题,是因为buf虽然只分配了2字节,其实buf+2后面有一段内存是已经被映射好的;
如果强制使用,可能会把数据写到别的block里,产生脏数据,导致写坏了。**
2.尝试写无效地址,无效地址被定义成非userspace,或者非mappingArea的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
long a=0xffff;
long* buf =(long*)a;
*buf=1;
printf("buf is %p\n",buf);
return 0;
}
运行结果:
Program received signal SIGSEGV, Segmentation fault
承接上个问题,继续测试,验证程序初始化时,通过计算char*p =sbrk(0)做推算,程序可用的heap地址范围是200K,
具体是p前面72k的地址,P后面128K的地址;
int main()
{
char* buf = new char[2];
char* p = (char*)buf;
for (int i=0;i<10000000;i++)
{
*p=0;
printf("%d %p\n",i,p);
p++;
}
return 0;
}
运行结果:
132063 0x17bbfff
段错误 (核心已转储)
3.new,delete /malloc,free 不匹配或者重复delete同一内存块;或者释放一段没有分配的内存,无效地址
int main()
{
char* buf = new char[2];
delete buf;
delete buf;
return 0;
}
* Error in `./test1’: double free or corruption (fasttop): 0x00000000009adc20 *
int main()
{
char* buf=(char*)0x001;//奇怪的是如果释放一个空指针,并无崩溃产生。
free(buf);
// delete buf;
printf(“END\n”);
getchar();
return 0;
}
4.除零崩溃
int main()
{
int a=0;
int b=1;
int c=b/a;
return 0;
}
浮点数例外 (核心已转储)
Program terminated with signal SIGFPE, Arithmetic exception.