How can C language return a character pointer in a function?

In C language, there are several ways to return a character pointer in a function.

  1. Return a pointer directly to a character array.
char* getString() {
    char str[] = "Hello";
    return str;
}

However, this method has a problem because once the function returns, the memory space for the local variable “str” will be released, causing the returned pointer to point to an invalid memory address.

  1. Return a pointer using a static local variable.
char* getString() {
    static char str[] = "Hello";
    return str;
}

The lifetime of a static local variable extends to the entire execution of the program, so the returned pointer remains valid. However, it should be noted that static local variables are not thread-safe, so if the function is used in a multi-threaded environment, appropriate thread synchronization measures need to be added.

  1. Return a pointer by using dynamic memory allocation.
char* getString() {
    char* str = malloc(sizeof(char) * (strlen("Hello") + 1));
    strcpy(str, "Hello");
    return str;
}

Allocate a block of dynamic memory by calling the malloc function, copy the string to that memory, and then return a pointer to that memory. However, it is important to manually call the free function to release that memory after use to prevent memory leaks.

  1. Use static global variables to return a pointer.
static char str[] = "Hello";

char* getString() {
    return str;
}

The scope of a static global variable is the entire program, so the returned pointer remains valid. Like static local variables, static global variables are also not thread-safe, so appropriate thread synchronization measures need to be added when using the function in a multi-threaded environment.

bannerAds