-2

I can allocate memory for pointer to struct bmp_ptr and I can check if the pointer is valid. But I need to allocate memory for header or dib member, how could I check that the malloc() was successful? I can malloc(), but using type cast means that the resulting pointer from malloc() would disappear. How could I declare the nested type?

header:
typedef struct BMP_DIB BITMAPINFOHEADER;
// BMP_DIB definition follows..

// BMP_FILE_struct definition follows:
    typedef struct BMP_FILE_struct {
      BMPHEADER header;
      BITMAPINFOHEADER dib;
    } BMPFILE;

main inside function:

BMPFILE * bmp_ptr;
bmp_ptr = malloc(sizeof(BMPFILE));
if (bmp_ptr == NULL) return NULL;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
John Boe
  • 3,501
  • 10
  • 37
  • 71
  • 1
    Exactly the same way as for whole struct? – zubergu Feb 17 '15 at 14:16
  • 1
    When a given `malloc()` fails you should consider `free()`ing the previous successful `malloc()`s, and also IMHO, one line `if` statements are confusing in the long run, they don't improve your coding style, the make it worse. – Iharob Al Asimi Feb 17 '15 at 14:18
  • 5
    Allocating the structure will allocate space for the members. You don't need to allocate them separately unless they are pointers. – interjay Feb 17 '15 at 14:19
  • 1
    "using type cast means that the resulting pointer from malloc would disappear." -- I don't understand, can you give some code example (the code given looks OK), I don't see what's the question. – mafso Feb 17 '15 at 14:21
  • It's not clear to me what pass after sizeof: ` bmp_ptr->header = malloc(sizeof(bmp_ptr->header));` this is not possible, so what type to pass there? How? – John Boe Feb 17 '15 at 14:24
  • Did you read my comment above? – interjay Feb 17 '15 at 14:30

1 Answers1

1

[Added after the comments]

TL;DR - You don't need to allocate dynamic memory [or, check for the address is NULL or not] for compile time allocated variables. They will always have defined memory location and cannot be NULL.

As your header and dib are not pointer variables, you don't need to malloc() separately for them. malloc()-ing for bmp_ptr will allocate memory for them both.


[Currently outdated]

Point 1. You need not and please do not cast the return value of malloc() and family.

Point 2. Anyways, Casting does not change the return value, it is related to the type.

for head or dib member, how could I check that the malloc was successful?

you need to check against NULL for bmp_ptr->header.

  • if malloc() is successful in allocating memory you'll have a non-NULL value.
  • if malloc() fails, it'll return NULL.

Same goes for dib also.

Note : Considering header and dib are pointer type variables. If they are not pointers, then no need to allocate memory using malloc().

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261