问题描述:

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)

网友答案:

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.

网友答案:

If you use malloc to allocate memory, it will remain allocated until you explicitly call free on it, regardless of how it's passed around between functions, returned, etc.

相关阅读:
Top