Re: malloc inside function (I know... I *did* search google first ;)
- From: Lawrence Kirby <lknews@xxxxxxxxxxxxxxx>
- Date: Wed, 24 Aug 2005 13:41:59 +0100
On Tue, 23 Aug 2005 16:36:59 -0400, Charles M. Reinke wrote:
....
>> /* Untested code follows */
>> long initialize_f(float *f) {
>> int i;
>> long n = 100;
>> f = malloc((size_t)n * sizeof *f);
>>
>> for(i=0; i<n; i++) {
>> f[i] = 0; /* or whatever initialization value you want */
>> } /* for i */
>>
>> return n;
>> } /* initialize_f */
>>
>> -Charles
>>
>>
>
> Of course, I made (at least) 2 errors--f must be passed by address, i.e.
> long initialize_f(float **f) {
> /* corrected code*/
> }
> and the return value of malloc should ALWAYS be checked for NULL, i.e.
> *f = malloc((size_t)n * sizeof **f);
> if(*f==NULL) {
> /* error handling code here */
> }
> else {
> /* initialization code here */
> }
> ...
Or IMO better still make the pointer the return value of the function
float *initialize_f(long *pn)
{
long i;
long n = 100;
float *f = malloc((size_t)n * sizeof *f);
if (f != NULL) {
for (i=0; i<n; i++) {
f[i] = 0; /* or whatever initialization value you want */
}
if (pn != NULL)
*pn = n;
}
return f;
}
Functions that allocate memory commonly return a pointer to the memory
allocated. That pointer is the primary return value from the function and
a null return value can be used to indicate failure as other functions
like malloc() do. The size value may or may not be needed depending on
context. The code allows a null pointer to be passed if it is not needed.
If it is never needed the pn parameter can be omitted completely from the
function definition, and then the float * return is certainly more natural
than using a float ** parameter and no return value.
Also some thought should be put into the function name. "initialize_f" is
a misleading name for a function that allocates the array, not just
initialises it.
Lawrence
.
- Follow-Ups:
- References:
- malloc inside function (I know... I *did* search google first ;)
- From: spasmous
- Re: malloc inside function (I know... I *did* search google first ;)
- From: Charles M. Reinke
- Re: malloc inside function (I know... I *did* search google first ;)
- From: Charles M. Reinke
- malloc inside function (I know... I *did* search google first ;)
- Prev by Date: Re: Parse tokens from a string
- Next by Date: Re: Why can't the parameter be const in this program?
- Previous by thread: Re: malloc inside function (I know... I *did* search google first ;)
- Next by thread: Re: malloc inside function (I know... I *did* search google first ;)
- Index(es):
Relevant Pages
|