:: Re: [DNG] int essid_alloc is causin…
Etusivu
Poista viesti
Vastaa
Lähettäjä: Rainer Weikusat
Päiväys:  
Vastaanottaja: dng
Aihe: Re: [DNG] int essid_alloc is causing valgrind to report a series of errors
Edward Bartolo <edbarx@???> writes:
> The problem according to my logic seems to be result is used in a
> branch control expression before it is initialised. However, I am
> emailing this to have other opinions.
>
>
> int essid_alloc(
>     size_t length,
>     char ** result
> ) {
>     char * tmp;

>
>     if(length==0 || !result)
>         return EINVAL;

>
>     tmp = (char *) calloc(length, 1);

>
>     if(!tmp)
>         return ENOMEM;

>
>     *result = tmp;

>     
>     return 0;
> }


result can't be uinitialized because it's an argument the caller must
provide. *result may be uninitialized but this doesn't really matter
unless the caller uses it regardless of the function return value. It
would be helpful to know what valgrind actually prints.

OTOH, the function above is equivalent to just doing a

char *essid;

essid = calloc(length, 1);
if (!essid) /* ENOMEM */

in the caller and IMHO, the whole function should be removed. There's
also no point in casting the result of any memory allocation routine _in
C_ as a void * will automatically be converted to whatever type was
asked for on assignment (and there are rare cases where this may mask an
actual error[*]).

[*] In particular, using calloc without a prototype in scope will cause
    the compiler to assume that it returns and int. This will work on a
    32-bit system because the sizeof of a pointer is == sizeof(int) but
    will fail on 64-bit (I had to mispleasure to debug this once when
    moving some 'working' 32-bit Linux code to Solaris 8 on Sparc ...).