-3

I have seen an issue when I try to create a function for concatenating string, and the program have built successfully with no compile time error, but when it run, my program have crashed. However, when I write the code directly into int main(), the program have run smoothly without error.
Is there any one can explain?

The code that causes program crash is:

...
inline char *concatStr(char *target, char *source){
  return copyStr(_endOfStr(source), source);
}
int main(){
  char hello[MAX] = "Hello ";
  char world[MAX] = "World!!\n";
  concatStr(hello, world); //create "Hello World!!\n" by adding "World!!\n" to end of "Hello "
  cout << hello; //I want display "Hello World!!"
  return EXIT_SUCCESS;
}

The replacement code is:

...
int main(){
  char hello[MAX] = "Hello ";
  char world[MAX] = "World!!\n";
  copyStr(_endOfStr(hello), world);
  cout << hello;
  return EXIT_SUCCESS;
}

function char *copyStr(char *target, char *source) overwiting target and returning pointer which point to null in target

function char *_endOfStr(char *str) returning pointer which point to null in str

Ramsharan
  • 2,054
  • 2
  • 22
  • 26
DMaster
  • 603
  • 1
  • 10
  • 23
  • You should _probably_ be using `std::string`: http://powerfield-software.com/?p=829 – paxdiablo Apr 12 '15 at 12:35
  • There's no obvious reason why those two snippets should give different behaviour, unless the code you haven't shown us (like the implementation of `copyStr` and `_endOfStr`) causes undefined behaviour, or `MAX` isn't large enough for the result. In any case use `std::string` and avoid all this dangerous messing around with fixed arrays. – Mike Seymour Apr 12 '15 at 12:36
  • MAX = 255 in my code – DMaster Apr 12 '15 at 12:45
  • `_endOfStr` may be using a [reserved identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris Apr 12 '15 at 12:50

2 Answers2

2

You have a typo on your crashing code:

return copyStr(_endOfStr(source), source);

should be

return copyStr(_endOfStr(target), source);

I don't have a C++ compiler at hand right now, but that should fix it.

-1

Since you use c++, instead of C, use string instead of char*.

Your code should look sometjing like this:

#include <string>
...
int main(){
  std::string hello = "Hello ";
  std::string world = "World!!\n";
  std::string helloWorld = hello + world;
  cout << helloWorld;
  return EXIT_SUCCESS;
}
Jasper
  • 6,076
  • 2
  • 14
  • 24