简体   繁体   English

在C中返回分配的指针

[英]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. 如我所料,它会打印10个X Would it behave like this on any platform with any compiler? 在具有任何编译器的任何平台上,其行为都将如此吗? Is the memory still malloced after getStr() returns? getStr()返回之后,是否仍在getStr()内存?

(I don't want to pass the pointer as argument :D) (我不想将指针作为参数传递给:D)

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

Yes, the code looks valid and the behavior should be reliable with any C compiler. 是的,代码看起来有效,并且任何C编译器的行为都应该可靠。

And, yes, the memory is still allocated after getStr() returns. 而且,是的,在getStr()返回之后仍会分配内存。 So the call to free() is also correct. 因此,对free()的调用也是正确的。

Don't forget to check if malloc() returns NULL , in the event there is insufficient memory. 如果malloc()不足,请不要忘记检查malloc()返回NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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