lukasrozs
lukasrozs

Reputation: 123

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)

Upvotes: 1

Views: 108

Answers (2)

Jonathan Wood
Jonathan Wood

Reputation: 67195

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.

Upvotes: 3

Mureinik
Mureinik

Reputation: 311143

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.

Upvotes: 3

Related Questions