0
int capacity =4;
struct Stack* stack =
    (struct Stack*) malloc(sizeof(struct Stack));
stack -> capacity = capacity;
stack -> top = -1;
stack -> array = (int*) malloc(stack -> capacity * sizeof(int));

What size will be allocated to stack and array. does array memory allocation will come under stack or it will be allocated separately.

Muntasir
  • 798
  • 1
  • 14
  • 24

2 Answers2

1

The only definitive statement that may be made about sizes is that the memory pointed to by stack will be sizeof(struct Stack) and the memory pointed to be stack->array will be 4 * sizeof(int). (Assuming that malloc() doesn't fail to allocate memory, in which case it returns NULL).

sizeof(struct Stack) is implementation defined - which means it varies between compilers, compiler settings, host systems, etc. sizeof(int) is also implementation defined.

Practically, sizeof(struct Stack) will be at least the sum of sizes of its members. A compiler may introduce additional padding between members. The amount of padding varies between compilers. (That's the simple explanation - the more complete explanation would go into alignment requirements for each type).

Unless all the members are of type char, unsigned char, or signed char (which have size 1 by definition), or arrays of those types, their size is implementation defined.

There is also no guaranteed relationships between the addresses returned by two different malloc() calls. They may be "together" (e.g. one immediately after the other in memory), but they may be completely separate.

Peter
  • 35,646
  • 4
  • 32
  • 74
0

Assuming the definition of Stack is like this:

typedef struct Stack{
    int capacity;
    int top;
    int *array;
} Stack;

Then the amount of allocated space for *stack should be sizeof(int) /* for capacity */ + sizeof(int) /* for top */ + *X* /* for *array */ (i.e- the sum of all the members' sizes of the struct).

On the other hand, amount of allocated space for array will be capacity*sizeof(int).

The allocations of *stack and *array are done independently in your case - because when you are making allocation for *stack, you are not constructing any array - you are just allocating for a pointer (along with other struct members) - which can not only be used to create an array, but can also be used to point a single int variable. After that allocation, you made an allocation for an array using the pointer you just created. The later allocation (*array) might be made adjacent to your previous allocation (*stack) - but it depends on the OS.

*X* : The size of a pointer depends on the architecture of you PC (i.e- your processor, RAM capacity, OS version (Win/Linux/Mac,x86/x64)), compiler options, as well as what type of pointer it is (i.e- is it an int pointer, or a double pointer). (Reference 1,2,3; and an example)

Muntasir
  • 798
  • 1
  • 14
  • 24