Take the 2-minute tour ×

Is the following code acceptable. That is, is this the right way to do a malloc?

This is the minimal code that I could get to work for my situation. I think it's 'the right way to do it' but I am super-new to C and don't have much of a clue overall. I read several related SO posts but none seem to exactly match this situation. Comments?

#include <stdio.h>

// example of calling a function that creates a dynamically sized array and
// returns it to a caller that doesn't know or care about the size of the array

char* return_char_array(){
     // for the sake of the example, we determined the size to be 100
     char *f=malloc(100*sizeof(char));
     // stick something in the first couple of elements for test purposes
     return f;

int main(){
    // we want this function to remain ignorant of the size or other workings 
    // of the array, so, no '[]' or 'malloc'
    char *wipc = return_char_array();
    // well i guess it cares a little, because we assume there are at least 2 elements...
    return 0;
share|improve this question
What is your question? –  unwind Jul 4 '12 at 14:32
If this is homework add the homework tag –  jacknad Jul 4 '12 at 14:35
'Is this the right way to accomplish calling a function that creates and returns a dynamically sized array'? –  GregT Jul 4 '12 at 14:37
It's not literally homework in the sense that I'm not taking a course or anything like that. –  GregT Jul 4 '12 at 14:38
Your comment says no '[]', but you use *(wipc+1), which is exactly the same as wipc[1]. –  ugoren Jul 4 '12 at 15:13
add comment

7 Answers

up vote 0 down vote accepted

No this is a bad idea and doesn't make much sense. The code that is allocating the memory needs to be responsible for freeing it, or you will have a great potential for memory leaks.

Typically you would write algorithms like this:

// caller.c

#include "stuff.h"  // the code uses the code module "stuff"

void caller (void)
  int* array = malloc(N * sizeof(int));

  do_stuff(array, N);



// stuff.h

void do_stuff (int* array, int size);


// stuff.c

#include "stuff.h"

void do_stuff (int* array, int size)

With this program design, "do_stuff()" doesn't need to care about memory allocation, it just executes its algorithm. Nor does anyone have to worry about memory leaks, because allocation and freeing is done from the same place.

Also, with this design, do_stuff() will work just as fine with statically allocated memory (simple arrays).

This design is pretty much the norm in C. The whole Windows API uses this design, as one example.

share|improve this answer
why was this answer down voted? –  Dave Jul 4 '12 at 14:55
I'm not the downvoter, but returning an object obtained by malloc is not bad style. In fact it's one of the only real uses of malloc except for working with data that's too large to reliably keep on the stack. The whole point of malloc is creating objects of dynamic storage duration; in your usage, it's equivalent to an object of automatic storage duration except that it can be bigger than would fit on the stack. –  R.. Jul 4 '12 at 15:28
@R.. If you find yourself returning non-constant pointers to dynamic memory outside the module where it was allocated, then that is bad style, not only because of the potential for memory leaks but also because it breaks encapsulation and good object-oriented design. Why should someone else be responsible for cleaning up your trash? This answer isn't taken out of the blue, I have plenty of experience of debugging crappily written programs in search of memory leaks. In 9 out of 10 cases, the memory leaks come from bad program design. –  Lundin Jul 5 '12 at 9:47
No, it doesn't break object-oriented design; it's absolutely necessary to object oriented design. An object-oriented library will have functions of the form myobject *myobject_create(...); and void myobject_destroy(myobject *); –  R.. Jul 5 '12 at 11:04
@R.. If myobject is an opaque (incomplete) type I would agree. Or if it was a const pointer. If it is not either of those two, it is bad design and breaks oo. –  Lundin Jul 5 '12 at 11:18
show 6 more comments


Use f[0] instead of *f and f[1] instead of *(f + 1). Same goes for wipc. Don't forget to call free.

share|improve this answer
add comment

I think it's OK in this situation. But remember to free the memory allocated :)

share|improve this answer
add comment

There is no advantage whatsoever for any function to not know the size of an array it's working with. The comment requires explanation.

share|improve this answer
Indeed, 'main' needs to know the size of the thing that 'return_char_array' created; what i meant was, 'main' shouldn't need to know about it in advance. It should let 'return_char_array' create whatever sized array it needs, as opposed to 'main' doing the malloc itself or specifying a fixed array size. (I hope I'm making sense). –  GregT Jul 4 '12 at 14:36
Ok, but this only works for this very trivial example. I'd have written so that return_char_array takes a parameter that specifies the number of elements in the array. –  James Jul 4 '12 at 14:40
Agreed. So that parameter would be an int pointer, and the function would still return the malloc'd pointer like it does now, correct? –  GregT Jul 4 '12 at 14:41
Just an int: char* return_char_array(int elements), it would behave the same –  James Jul 4 '12 at 16:32
add comment

On the very first sight i acknowledge that you dont free() your malloced space, wich is bad (Memory-Leak). Thats the only real "fault" i can see. But, if you want more insight in form of a Code-Review you might post it on the Stackexchange Site "Code-Review", as this Site is more in solving actual problems and errors.

share|improve this answer
add comment

Well, it is really minimal code. I would rather to put the extra mark bytes at the end of the buffer, and remember to add the extra 2 bytes to the buffer length when malloc

Those 2 bytes are reserved for internal usage, and should not be exposed to user.

share|improve this answer
add comment

A few comments,

1)Pl. do proper error handling. What happens if malloc fails?

if (NULL == f)
   //Take actions ..Exit with error or return NULL..

2)Pl. avoid hardcoded values like 100 ( may have a #define MAX 100)

3)Pl. make sure to free the memory properly.

share|improve this answer
add comment

Your Answer


