0

I am writing a function that should return Hello world!, but it returns Hello Wo.. I added a cout right before my return statement to check the value and it is correct.

I pass two parameters into the function, one and two, and my function combines the word and returns. I wrote a loop to transfer one into a new char so the original passed value isn't effected since I am accessing it's array.

Function:

char* myStrCat(char inputOne[], char inputTwo[]){
    int sizeOne = myStrLen(inputOne);
    int sizeTwo = myStrLen(inputTwo);
    char functionTemp[100];

    for(int tempReplace = 0; tempReplace < sizeOne; tempReplace++){
        functionTemp[tempReplace] = inputOne[tempReplace];
    }

    for(int i = 0; i < sizeTwo; i++){
        functionTemp[i + sizeOne] = inputTwo[i];
    } 
    cout << "check: " << functionTemp << endl;
    return functionTemp;
}
Vincent
  • 99
  • 5

1 Answers1

4

functionTemp is a local variable and myStrCat() returns address of local variable, read the compiler warning.

Instead of taking functionTemp as a local static array take functionTemp as pointer and allocate memory dynamically using new for pointer and returns the pointer.

Edit :

char* myStrCat(char inputOne[], char inputTwo[]){
        int sizeOne = strlen(inputOne);
        int sizeTwo = strlen(inputTwo);
        int bytes = sizeOne + sizeTwo;
        char *functionTemp = new char [bytes + 1];/* allocating memory dynamically for functionTemp */


            for(int tempReplace = 0; tempReplace < sizeOne; tempReplace++){
                    functionTemp[tempReplace] = inputOne[tempReplace];
            }

            for(int i = 0; i < sizeTwo; i++){
                    functionTemp[i + sizeOne] = inputTwo[i];
            }
            cout << "check: " << functionTemp << endl;
            return functionTemp;
    }

And in calling function once you got the concatenated string/dynamic address, free it using delete to avoid memory leakage. A simple calling function looks like

int main() {
        char *temp = NULL;
        temp = myStrCat("Stack","overflow");/* temp holds dynamic address */
        cout<<temp<<endl;
        /* free the dynamically allocated memory */
        delete [] temp ;

        return 0;
}
Achal
  • 11,821
  • 2
  • 15
  • 37