abhinavkulkarni
abhinavkulkarni

Reputation: 2399

Query about declaring size in header files

I have a structure that contains a pointer to a fixed sized memory.

Say,

// Structure of a page
struct Page {
public:
    // Number of slots
    unsigned short numSlots;
    void *data = malloc(PF_PAGE_SIZE);
};

I want to put this declaration in a header file. Should I also explicitly put the malloc part in it or it should only contain void *data and no details about how much memory the pointer points to?

In short should the declaration look like above or resemble the following:

// Structure of a page
struct Page {
public:
    // Number of slots
    unsigned short numSlots;
    void *data;
};

Upvotes: 0

Views: 81

Answers (1)

Alok Save
Alok Save

Reputation: 206528

You cannot use the first syntax, it will give you a compiler error.
As for the correct approach, the answers differ depending on whether you are using C or C++.

In C++:

You should only declare the structure member in the header file.
You initialize it in the Member Initialization List in C++ source file.

Header file:

// Structure of a page
struct Page {
public:
    // Number of slots
    unsigned short numSlots;
    void *data;
};

Source File:

Page::Page():data(malloc(PF_PAGE_SIZE))
{}

Notes:

  • It is always better to use a smart pointer rather than a raw pointer.
  • Also, In C++ one would usually use new and not malloc but since your pointer is of the type void, malloc might also be fine depending on the usage.
  • The code above just answers your immediate Q, There are still other important things to be considered.You still need to follow the Rule of Three since you have a pointer member with dynamic memory allocation for your structure.

In C:

In C, there are no Member Initialization lists, so you have to initialize the member after you create an object of the structure.

Header file:

// Structure of a page
struct Page {
    // Number of slots
    unsigned short numSlots;
    void *data;
};

Source File:

struct Page obj;
obj.data = malloc(PF_PAGE_SIZE);

Upvotes: 1

Related Questions