Function Returning Pointer

Hi guys.

how a functions such fdopen, ... can return pointer?
are these functions use static memory(variables)?

No, they simply use malloc inside the function.
Just a quick example of how it could work (REALLY JUST AN EXAMPLE)

typedef struct {
    int fd;
    int mode;
     /* a lot of variables to describe the filestream */
}FILE;

FILE *fopen(char *path, char *mode) {
    FILE *ret;
    ret = (FILE *) malloc(sizeof(FILE));
    /* do some processing */
    return ret;
}

Accordingly I assume that fclose() will then make a free() call to free the memory

but when when returning from a function, all memory returned to OS isn't it?

No that will happen only when the program exits otherwise all memory allocated is in use by the process.

1 Like

Thanks I got it.
Another question is:
How about allocating memory with alloca function? because it allocates memory from stack frame.

This question about alloca can start a flame war...some are proponents of it (i am not) but why would you want to allocate memory from the stack which to begin with is small...and the fact that alloca is not portable. Better to leave it to malloc which gets it from the bigger sized data segment. In any case use your best judgement. If i were you i wont use alloca but that's just me.

1 Like

alloca memory's main advantage, and main problem, is that it's fairy gold -- it vanishes. When your function returns, anything it's allocated with alloca becomes invalid (and potentially overwritten with trash). This means you don't have to free it yourself -- but you can't return it, either. You can pass it into a function, but can't pass it out of the function that allocated it.

alloca is fairly portable in one sense -- its convenience and (in some cases) performance advantage are tempting enough that you'll find it almost anywhere an implementation of it's even possible. But it's not actually defined by standard, and not actually possible everywhere. The long-standing flamewar over it is whether it should be considered a de-facto standard. Pros are it's simplicity and performance advantages. Its cons are potential bugs from implementations that don't do what you expect, limited stack memory, potential nonexistence if you port your code anywhere, and it not doing what you'd expect if you're used to malloc().

I think the best practice for returning a pointer is to take a pointer in the first place. Just use the memory you were given, then give it back. Where the memory came from and why becomes someone else's problem :wink:

1 Like