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