Can/Why using char * instead of const char * in return type cause crashes?

后端 未结 5 1661
醉梦人生
醉梦人生 2021-01-05 15:12

I read somewhere that if you want a C/C++ function to return a character array (as opposed to std::string), you must return const char* rather than char*. Doing the latter m

5条回答
  •  盖世英雄少女心
    2021-01-05 15:27

    What you were told is not true.

    Returning a const char * can improve the semantics of a function (i.e. don't mess with what I'm giving you) but returning a char * is perfectly fine.

    However, in either case, you must make sure that you return a char * or const char * that was allocated on the heap in my_function (i.e. allocated using malloc or new), otherwise whenever my_function returns, the memory for the [const] char * will be deallocated, and you will be accessing an invalid pointer.

    And finally you must remember to free or delete the [const] char * that's been returned to you once you're done with it, or you will leak memory. Aren't C/C++ such great languages?

    So, in C, you would have

    const char *my_function() {
        const char *my_str = (const char *)malloc(MY_STR_LEN + 1);  // +1 for null terminator.
        /* ... */
        return my_str;
    }
    
    int main() {
        const char *my_str = my_function();
        /* ... */
        free(my_str);
        /* ... */
        return 0;
    }
    

提交回复
热议问题