Is this a memory leak since memory was allocated on stack?

I have a device that can either be a "Router" or a "Switch". I use the below function, passing it an enum that returns me the string. My question is that the memory for whoami is allocated on the stack. When this function devicetype_string finishes, the stack is destroyed. Would this not cause an issue when i use a pointer thats pointing to a memory allocated on the stack?

The current code works. I just want to understand why it works. I would presume that a cleaner and a portable solution would be to malloc memory to hold whoami (so that it goes to the heap) and the calling function should free that memory.

This is the current program:

char *devicetype_string (FwdrType devicetype)
{
    char *whoami;

    switch (devicetype)
    {
        case FWDR_TYPE__ROUTER:
            whoami = "Router";
            break;

        case FWDR_TYPE__SWITCH:
            whoami = "Switch";
            break;

        default:
            whoami = "Fwder Type UNKNOWN";
    }

    return whoami;
}

foo()
{
    . . .
    FwderType abc = FWDR_TYPE__ROUTER;

    printf ("%s", devicetype_string(abc));
}

It's not memory leak, and it's not undefined behavior.

In the function devicetype_string , whoami points to a string literal in all paths. String literals have static storage duration, they don't need to be freed.


It works because you're returning a pointer to a static string, which isn't created on the stack - they instead have static storage duration, meaning they will be valid for the duration of your program.

See this question

Something else to note:

String literals are typically stored in the read-only-data section. Attempting to assign a writeable char* to a string literal, which is probably read only (probably because where literals are stored is actually platform specific) and then modify the contents will trigger undefined behaviour, often a segmentation fault (attempting to modify the read-only-data section).

GCC will fail to compile, not allowing assigning a writeable char* to a string literal.

A better implementation would not be to assign your char* pointer, but just to return the address of the string literal as a const char*

const char *devicetype_string (FwdrType devicetype)
{
    switch (devicetype)
    {
        case FWDR_TYPE__ROUTER: return "Router";
        case FWDR_TYPE__SWITCH: return "Switch";
        default: break;
    }
    return "Fwder Type UNKNOWN";
}
链接地址: http://www.djcxy.com/p/79846.html

上一篇: C程序的堆栈和堆内存

下一篇: 这是内存泄漏,因为内存分配在堆栈上?