给出正确的输出后给出错误分段错误(核心转储)
问题描述:
下面给出的代码给出了正确的输出总线,然后打印出分段错误(核心转储)错误。我有这个错误很多次,并试图寻找它,但从来没有明确的想法。我使用gdb,并得到以下错误:给出正确的输出后给出错误分段错误(核心转储)
程序接收到的信号SIGSEGV,分段故障。 0x0000003c0c49d4d1中的std :: basic_string的, 从/usr/lib64/libstdc++.so.6
的std ::分配器> ::〜basic_string的()()在哪里我尝试访问无效的内存地址。如果我做了它是如何给出正确的结果。我是unix和C++的新手。请解释。
代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
string convMMDDYY(string str)
{
char *dateToConv= new char[str.length()+1];
strcpy(dateToConv,str.c_str());
char *ch = strtok(dateToConv,"-");
string date="";
string time="";
while(ch!=NULL)
{
date = date + ch[strlen(ch)-2] + ch[strlen(ch)-1] + "/" ;
ch=strtok(NULL,"-");
}
date = date.substr(0,8);
string convDate = date.substr(3,2) + "/" + date.substr(6,2) + "/" + date.substr(0,2);
unsigned found = str.find_last_of("-");
time = str.substr(found+1,8);
string convFormat = convDate + " " + time;
cout<<convFormat<<endl;
}
int main()
{
string a="2014-08-26-22:10:55.452549893";
convMMDDYY(a);
return 0;
}
的程序输入日期在2014-08-26-22:10:55.452549893格式并给出作为14年8月26日22点10分55秒
,然后输出给出错误分段错误(核心转储)
答
convMMDDYY
声明为返回string
但您没有任何return
语句,导致函数到达末尾时出现未定义的行为。
(您有其他各种问题,例如,您从不delete[]
内存您new[]
'd,并且缺乏错误检查,以便意外的输入导致您的代码缓冲区溢出或访问数组的边界。
正确启用的编译器警告会告诉OP有关...以'-Wall -Wextra'开始,然后查阅[手册](https://gcc.gnu.org/onlinedocs/gcc-4.9.1 /gcc/Warning-Options.html#Warning-Options)还有什么可用的。 – DevSolar 2014-08-29 10:46:54