Question

Folks I am trying to understand if there is any thing in the following piece of code that will cause it to fail on 64 bit platforms. My main concern is whether some type conversions are happening that are not suitable for 64 bit. Do not pay too much attention on the actual numbers assigned to the variables as i made them up just for this example. My main concern is the type conversion issues happening between long and int and size_t and any other issues you may see.

#define NL_AREA 40      
#define NS_AREA 38     
#define NB_EXTRA (1536 - NS_AREA * NL_AREA) 

main()
{
    long int  bufsize;
    int       obssize, nelm, nbuf;
    int ncol, ndet = 10;
    void      *result;

    obssize = xxx; /* some size */
    bufsize = (long)obssize * (NL_AREA * NS_AREA + NB_EXTRA);
    ncol = 50;
    nbuf = ncol * ndet;
    nelm = 1;
    result = Buf_Init(bufsize, nelm, nbuf);
}

void * 
Buf_Init( size_t elm_size, 
          int    nelm_buf, 
          long   nbuf )
{
    long buf_size;
    void *p;
    buf_size = ((long) elm_size) * nelm_buf;
    if ((p = (void *)malloc(buf_size)) == NULL)
      return NULL;
    else
      return p;
}
Was it helpful?

Solution

I could comment on type conversions, but... why ponder about unexpected type conversions in your code when you can avoid them completely? If portability is important, then don't use the default primitive data types. Use stdint.h instead.

  • Swap int for int32_t.
  • Swap long for int32_t.
  • Keep size_t as it is, or swap it for uint32_t in case it matters. Most likely it does not.

And suddenly the code turned 100% portable.

Other comments:

  • Why would you do (void *)malloc(buf_size)? Casting from void* to void* doesn't make any sense.
  • For a hosted system, main() must always return int. Implicit int has been removed from the C language 15 years ago.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top