0

I am trying to create a specific case of a problem in my following code;

std::string id = "123456789123456789" // it can be different sized string too.
std::string my_id = "TEST_" + id;
char* temp_my_id = (char *) my_id.c_str();
strcpy(temp_my_id, my_id.c_str());
PRINT("my_id value : ", temp_my_id);

It is a legacy code in my project and I suspect the temp_my_id returns non-ascii character. Is this possible?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
SayMyName
  • 461
  • 5
  • 17
  • 1
    Could you explain what is the problem and what are you trying to do here? You’re copying the contents of a string to itself? Why and what’s the actual problem? – Sami Kuhmonen May 15 '20 at 09:08
  • 1
    From the [docs for `strcpy`](http://man7.org/linux/man-pages/man3/strcpy.3.html) _"The strings may not overlap"_ – Ackdari May 15 '20 at 09:10
  • Also, you're casting away const-ness. With all these real problems, I don't think we need to consider hypothetical problems about "non-ASCII" characters. – MSalters May 15 '20 at 09:11
  • In `strcpy(temp_my_id, my_id.c_str())` `temp_my_id` and `my_id.c_str()` point into the same memory buffer. This is an error as @Ackdari told already. – JATothrim May 15 '20 at 09:16
  • Actually there is not a problem. It is about a problem possibility. I wonder if I don't any modification in the code can it return non-ascii chars. – SayMyName May 15 '20 at 09:17

2 Answers2

2
char* temp_my_id = (char *) my_id.c_str();
strcpy(temp_my_id, my_id.c_str());

source and destination can not have the same memory location in strcpy because both arguments are marked as restrict:

Bold test is mine:

restrict is a keyword (in C, not in C++) that can be used in pointer declarations. By adding this type qualifier, a programmer hints to the compiler that for the lifetime of the pointer, only the pointer itself or a value directly derived from it (such as pointer + 1) will be used to access the object to which it points.

you can try

char a[] = "123";
char *b = a;

strcpy(b, b);

returns:

warning: ‘strcpy’ source argument is the same as destination [-Wrestrict]

again in C, in C++ it is also broken because source and destination can not overlap.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 1
    Thats not really an answer to the op's question regarding "non-ascii" characters but... good point! – Wolfgang May 15 '20 at 09:18
1

strcpy does not really care about the encoding, it copies until it finds a NULL byte. So you just have to be careful that

  • the source ends with a zero byte and contains none in the middle
  • the source is not longer than the destination
  • source and destination should not overlap

see strcpy vs. memcpy and http://www.cplusplus.com/reference/cstring/strcpy/

Wolfgang
  • 320
  • 3
  • 12