1

i have a problem.

i tried to proceede the following steps:

    char * str;
    char * s="Hello";
    int len = std::strlen(s);
        str=new char[len +10];
    strcpy_s(str,sizeof(str) ,s);

But the programm displays the error, which i write in the title.

If i replace the sizeof(str) with a number, for example 256, a pop up window appear with the message project.exe has triggered a breakpoint.

How can i solve this errors with strcpy_s?? Thank you!

Perilun
  • 53
  • 1
  • 2
  • 6
  • When standard library functions don’t do what you expect, look at the arguments you’ve calling them with. Print the value os `sizeof(str)`. – Pete Becker Oct 28 '17 at 21:09

2 Answers2

2

The sizeof(str) returns the size of char* which is (probably) either 4 or 8 (bytes) depending on the implementation. In your case it appears to be 4 which is not enough to hold the characters that make up the "Hello" literal plus the null terminating character. Since there is not enough space the strcpy_s function invokes undefined behavior. You need at least 6 bytes which is the number of characters + 1 byte for a null character. Also instead of str=new char[len + 10]; you probably meant str = new char[len + 1]; to accommodate for the \0 character. Hence your code should be:

#include <iostream>

int main(){
    char* str;
    char* s = "Hello";
    int len = std::strlen(s);
    str = new char[len + 1];
    strcpy_s(str, len + 1, s);
}

That being said prefer std::string to C-style character array.

Ron
  • 14,674
  • 4
  • 34
  • 47
0

sizeof(str) gives the size of char*, which is not the length of the allocated array. To fix this, you must give the allocated length. In this case this would be

strcpy_s(str, len + 10, s);
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • Can you please explain, why i have to write len + 10? I thought i have to make only len + 1, because of the '\0' for the end ? – Perilun Oct 28 '17 at 20:54
  • Because the second argument should be the size of the destination buffer. See http://en.cppreference.com/w/c/string/byte/strcpy for more details. – Olaf Dietsche Oct 28 '17 at 20:56
  • In the example, which is in the source, i see the following code part: char dst[strlen(src) + 1]; // +1 to accomodate for the null terminator, so why i have to make len +10 instead of len +1? And do i have allways to make len +10? I would be very thankful for a instruction! – Perilun Oct 28 '17 at 21:01
  • I have taken the 10 from your question, where you allocate `new char[len + 10];`. You are correct, that `len + 1` is sufficient. – Olaf Dietsche Oct 28 '17 at 21:05