Can I use "malloc" for local variables to return local variables?

Viewed 2548
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

char * upperCase(const char* s)
{
    char * ret = NULL;
    size_t length = strlen(s) + 1;
    ret = (char*)malloc(sizeof(char) * length);
    for (size_t i = 0; i < length; i++) {
        ret[i] = toupper(s[i]);
    }
    return ret;
}

int main()
{
    char* ret = NULL;
    char* input = "HelloWorld";
    ret = upperCase(input);
    printf("value = %s", ret);
    free(ret);
}

The above code takes a string as a parameter and copies the string. It then converts each element of the copied string to uppercase and returns it.

Compiler = GCC 6.2

If you use the malloc function, is it possible to return a local variable to terminate the function and release the memory? I do not have enough understanding of the scope that still has memory.

2 Answers
Related