Juhan Kelp
Juhan Kelp

Reputation: 13

char* return type acting strange

I am using visual studio. The following code will print nonsense in the console.

    #include <iostream>
    
    
    namespace tools {
        char* slice_to(const char arr[],char term) {
            char tulem[1000];
            char(*tul)[1000] = &tulem;
            int i = -1;
            do{
                i++;
                tulem[i] = (arr[i] == term) ? '\0' : arr[i];
            } while (arr[i]!=term);
            return *tul;
        }
    };
    
    
    int main() {
        std::cout<<tools::slice_to("This is a test!", '\0');
    }

But if I print something before calling the function it works fine. Why is that? The following code prints what I would expect:

#include <iostream>


namespace tools {
    char* slice_to(const char arr[],char term) {
        char tulem[1000];
        char(*tul)[1000] = &tulem;
        int i = -1;
        do{
            i++;
            tulem[i] = (arr[i] == term) ? '\0' : arr[i];
        } while (arr[i]!=term);
        return *tul;
    }
};


int main() {
    std::cout << "Bruh\n";
    std::cout<<tools::slice_to("This is a test!", '\0');
}

Also using the printf function outputs the correct result.

Upvotes: 1

Views: 58

Answers (1)

Quarra
Quarra

Reputation: 2695

You're trying to cout a local variable that is out-of-scope once the slice_to returns. As you're returning a ptr, no copy of the underlying data is being done - it's a pointer to memory that is no longer valid. As it's on the stack, it may not be overwritten (hence you're able to access the values under the address) but this is an error.

Try changing the return type of slice_to to std::string that will manage the underlying memory and will create a temporary object when the function exits - that should do just fine.

Upvotes: 4

Related Questions