简体   繁体   中英

Returning malloced pointer in C

I have the following program:

#include <stdio.h>
#include <stdlib.h>

char* getStr(int length) {
    char* chars = malloc(length + 1);
    int i;
    for(i = 0; i < length; i++)
        chars[i] = 'X';
    chars[i] = '\0';
    // no call to free()
    return chars;
}

int main(int argc, char** argv) {
    char* str;
    str = getStr(10);
    printf("%s\n", str);
    free(str);
    return EXIT_SUCCESS;
}

It prints 10 X 's, as I expected. Would it behave like this on any platform with any compiler? Is the memory still malloced after getStr() returns?

(I don't want to pass the pointer as argument :D)

如果您使用malloc分配内存,那么它将一直保持分配状态,直到您显式调用free为止,无论它在函数之间如何传递,返回等。

Yes, the code looks valid and the behavior should be reliable with any C compiler.

And, yes, the memory is still allocated after getStr() returns. So the call to free() is also correct.

Don't forget to check if malloc() returns NULL , in the event there is insufficient memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM