D
D
Danil Vaskevich2021-06-08 15:14:39
C++ / C#
Danil Vaskevich, 2021-06-08 15:14:39

How to solve "String is not null terminated" error?

I need to concatenate two strings with a space. The code itself compiles and runs, but after entering two lines, it throws the error "String is not null terminated".
Here is the code:

char* String::concat(const String& other)
{
  const char space[3]{ " \0" };
  
  
  String result(9999);
  
  

  strcat_s(result.string_, strlen(string_), string_);
  
  cout << result.string_ << endl;

  strcat_s(result.string_, strlen(space), space);
  
  cout << result.string_ << endl;

  strcat_s(result.string_, strlen(other.string_), other.string_);
  
  cout << result.string_ << endl;
  
  return result.string_;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2021-06-08
@DaniVffgf

You are using the strcat_s function incorrectly.
Traditionally in C (apparently due to the peculiarities of the PDP-11 machine), each line ends with a null character.
The meaning of strcat_s is that if the string is in a buffer of limited length and for some reason not null-terminated, the function will not get into the “left” memory, but will be limited to the size of the buffer. The second parameter should be the length of the buffer, not strlen, which defeats the whole purpose of the "safe" suffix.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question