How much memory gets allocated for the stack dynamically for this code?
#include<iostream>
using namespace std;
#define max_size 100
typedef struct stack
{
int top;
int capacity;
int items[max_size];
} stack;
stack* initialize(stack *s, int capacity)
{
s = (stack*)malloc((capacity)*sizeof(int) + sizeof(int) + sizeof(int));
s->top = -1;
if(capacity<1)
cout<<"invalid capacity !"<<"\n";
else
s->capacity = capacity;
return s;
}
I tried to avoid any extra memory allocation. I didn't use this line of code:
stack *s = (stack*)malloc(sizeof(stack));
because it will create a stack of max_size
of items. I want to strictly allocate memory for a stack which holds capacity
number of items. Is this the right way to achieve my goal? If it's not, then please provide me with the better code possibly with a modified structure definition. I'm getting the desired results for my code.
malloc((capacity)*sizeof(int) + sizeof(int) + sizeof(int));
This will not work, the compiler expects capacity
to be exactly 100 items, statically, since you declared the array member as such. You cannot underallocate memory for the struct and expect the program to behave in a certain way - it's undefined behavior in either language.
The correct solution for C++ is to use std::vector
or std::stack
etc instead. You should never use malloc
in C++ programs: it is plain dangerous since it doesn't call constructors etc and struct
in C++ is just a poor man's class.
The correct solution for C is to use a flexible array member:
typedef struct stack
{
int top;
int capacity;
int items[];
} stack;
...
stack *s = malloc( sizeof(stack) + sizeof(int[capacity]) );