char x[256] vs. char* = malloc(256*sizeof(char));

后端 未结 6 1467
日久生厌
日久生厌 2020-12-29 09:53

Someone here recently pointed out to me in a piece of code of mine I am using

char* name = malloc(256*sizeof(char));
// more code
free(name);
6条回答
  •  孤城傲影
    2020-12-29 10:22

    In the first code, the memory is dynamically allocated on the heap. That memory needs to be freed with free(). Its lifetime is arbitrary: it can cross function boundaries, etc.

    In the second code, the 256 bytes are allocated on the stack, and are automatically reclaimed when the function returns (or at program termination if it is outside all functions). So you don't have to (and cannot) call free() on it. It can't leak, but it also won't live beyond the end of the function.

    Choose between the two based on the requirements for the memory.

    Addendum (Pax):

    If I may add to this, Ned, most implementations will typically provide more heap than stack (at least by default). This won't typically matter for 256 bytes unless you're already running out of stack or doing heavily recursive stuff.

    Also, sizeof(char) is always 1 according to the standard so you don't need that superfluous multiply. Even though the compiler will probably optimize it away, it makes the code ugly IMNSHO.

    End addendum (Pax).

提交回复
热议问题