-3

exception in 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);
}

could you help me to solve it?

Michael M.
  • 2,556
  • 1
  • 16
  • 26
  • 1
    What exception? Do you mean segfault? Also, why do you use C string functions with C++? That's usually a bad idea if you don't know what you are doing and *why*. And one problem is, str2 is uninitialized pointer. – hyde Aug 14 '13 at 06:51
  • Besides missing allocations, look at http://stackoverflow.com/questions/236129/splitting-a-string-in-c –  Aug 14 '13 at 06:55
  • Your question is throwing an exception of not showing the exception... – NREZ Aug 14 '13 at 07:03

2 Answers2

5

str2 is an uninitialised pointer. strcpy does not allocate memory so is currently trying to write to an arbitrary address which you don't own and very likely isn't writable by your code.

You need to point str2 to valid memory before calling strcpy.

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

You should also free the memory later in your program

free(str2); // cannot dereference str2 after this point
simonc
  • 41,632
  • 12
  • 85
  • 103
  • thanks,but it will generate one error invalid conversion from void* to char* – Nadia Barjaste Aug 14 '13 at 08:35
  • @NadiaBarjaste I've updated my answer with the missing cast. (I forgot the cast is required by C++; it isn't required and is discouraged in C) – simonc Aug 14 '13 at 08:59
0

The problem is that you write in an uninitialized/random memory location by not initializing str2.

First solution:

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

Second (better solution): Do not use pointers in your code unless you have to:

std::string str2 = str1;

Also, consider using std::ostringstream for tokenization into std::strings and converting to int.

utnapistim
  • 26,809
  • 3
  • 46
  • 82