-3

strcpy() 中的异常;

void recid(string str,int *begin, int *end)
{
  char *f,*str2;

  const char c1[2]=":",c2[2]="-";
  strcpy(str2,str.c_str());
  f=strtok(str2,c1);
  f=strtok(NULL,c2);
  *begin=atoi(f);
  f=strtok(NULL,c2);
  *end=atoi(f);
}

你能帮我解决吗?

4

2 回答 2

5

str2是一个未初始化的指针。 strcpy不分配内存,因此当前正在尝试写入您不拥有的任意地址,并且很可能您的代码不可写。

您需要在调用之前指向str2有效内存strcpy

str2 = (char*)malloc(str.size()+1);
strcpy(str2,str.c_str());

你也应该free在你的程序后面的内存

free(str2); // cannot dereference str2 after this point
于 2013-08-14T06:47:19.837 回答
0

问题是您通过不初始化 str2 来写入未初始化/随机内存位置。

第一个解决方案:

str2 = new char[str.size() + 1];
strcpy(str2, str.c_str());
...
delete[] str2.

第二(更好的解决方案):不要在代码中使用指针,除非你必须:

std::string str2 = str1;

此外,考虑使用 std::ostringstream 将标记化为 std::strings 并转换为 int。

于 2013-08-14T08:53:42.707 回答