在给出正确的输出后给出错误分段错误(核心转储)

时间:2014-08-29 10:36:43

标签: c++ linux segmentation-fault

下面给出的代码在打印出分段故障(核心转储)错误之后给出了正确的输出总线。我已经多次遇到这个错误,并尝试过搜索它但从未对它有过清晰的认识。我使用gdb并得到以下错误:

编程接收信号SIGSEGV,分段故障。 std :: basic_string中的0x0000003c0c49d4d1,std :: allocator> :: ~basic_string()() 来自/ usr / lib64 / libstdc ++。so.6

我在哪里尝试访问无效的内存地址。如果我做了它是如何给出正确的结果。我是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格式输入日期并输出为08/26/14 22:10:55

然后给出错误分段错误(核心转储)

1 个答案:

答案 0 :(得分:2)

声明

convMMDDYY返回string,但您没有任何return语句,导致函数结束时出现未定义的行为。

(您还有其他各种问题,例如,您永远不会delete[]内存new[],并且缺少错误检查,因此意外输入会导致代码缓冲溢出或访问超出数组范围。)