pr123
pr123

Reputation: 19

Structure's int field gets modified after malloc() on the same structure's int*

#define MAX_NUM_STACKS_ALLOWED    10
#define MAX_PLATES_PER_STACK      5
#define NEW_STACKS_CREATION_INC   2

typedef struct stackOfPlates {
    int currentStackIndex;
    int currentStackTop[MAX_NUM_STACKS_ALLOWED];
    int currentMaxStacks;
    int **stackOfPlatesArray;
} stackOfPlates_t;

stackOfPlates_t *stackOfPlates_Init(void) {
    stackOfPlates_t *stackOfPlates = (stackOfPlates_t *)malloc(sizeof(stackOfPlates));

    stackOfPlates->stackOfPlatesArray = (int **)malloc(NEW_STACKS_CREATION_INC * sizeof(int *));
    stackOfPlates->currentStackIndex = 0;
    stackOfPlates->currentMaxStacks = NEW_STACKS_CREATION_INC;

    int i;
    for (i = 0; i < stackOfPlates->currentMaxStacks; i++) {
        stackOfPlates->stackOfPlatesArray[i] = (int *)malloc(MAX_PLATES_PER_STACK * sizeof(int));
        printf("%d\n", stackOfPlates->currentMaxStacks);
    }
    
    for (i = 0; i < MAX_NUM_STACKS_ALLOWED; i++) {
        stackOfPlates->currentStackTop[i] = -1;
    }
    return stackOfPlates;
}

void main()
{
    stackOfPlates_t *stackOfPlatesA;

    stackOfPlatesA = stackOfPlates_Init();
}

The output of the above code is:

I'm trying to malloc the 2D array (stackOfPlates->stackOfPlatesArray). After allocating memory for the NEW_STACKS_CREATION_INC number of stacks, I allocate memory for MAX_PLATES_PER_STACK for every stack. During this operation, I find that my stackOfPlates->currentMaxStacks gets modified to 0.

Could someone please explain why?

Upvotes: 1

Views: 32

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

In your code

 malloc(sizeof(stackOfPlates));

should be

malloc(sizeof(*stackOfPlates));

As you want to allocate memory for the structure type not the pointer to structure type.

That said, see this: Do I cast the result of malloc?

Upvotes: 2

Related Questions