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
*f=65;
*(f+1)=66;
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...
printf("%c,%c\n",*(wipc),*(wipc+1));
system("PAUSE");
return 0;
}
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:
_
_
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.