Happy New Year!
I have been struggling to find what causes the error I will explain below for some time now and I would be so very grateful for any help. I have the following code which, in principle, should implement a stack:
#include <stdio.h>
#include <stdlib.h>
void resize(int *nmax, int *d){
int i, *u;
*nmax *= 2;
u = (int *)realloc(d,sizeof(int)*(*nmax));
if(u == NULL){
printf("Error!\n");
exit(1);
}
d = u;
}
void push(int *n, int *d, int *nmax){
int u = *n , i;
if(u == *nmax) {
resize(nmax, d);
}
*(d + u) = u;
u++;
*n = u;
}
void pop(int *n){
int u = *n;
*n = u - 1;
}
int main(){
int *d, n = 0, i, nmax = 5;
d = (int *)malloc(sizeof(int)*nmax);
*(d+(n))= n;
n++;
*(d+(n)) = n;
n++;
*(d+(n)) = n;
n++;
//for(i = 0;i < n;i++)
//printf("%d\n",*(d+i));
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
push(&n,d, &nmax);
//pop(&n);
//pop(&n);
//pop(&n);
for(i = 0;i<n;i++)
printf("%d\n",*(d+i));
return 0;
}
It seems to behave normally until I un-comment the printf statement before the stack of push operations. The error I get is:
0
1
2
*** Error in `./a.out': realloc(): invalid next size: 0x0000000000f08010 ***
I am not sure I have explained it ok and if I didn't please let me know of any additional details I could add so as to make it more clear.
Thank you very much for your help!
EDIT:
With the hope that the code has now become a little more readable, this is what I have:
#include <stdio.h>
#include <stdlib.h>
void resize(int *sizeOfArray, int *myArray){
int i, *u;
*sizeOfArray *= 2;
u = (int *)realloc(myArray,sizeof(int)*(*sizeOfArray));
if(u == NULL){
printf("Error!\n");
exit(1);
}
myArray = u;
}
void push(int *pos, int *myArray, int *sizeOfArray){
int i;
if(*pos == *sizeOfArray) {
resize(sizeOfArray, myArray);
}
*(myArray + (*pos)) = *pos;
(*pos)++;
}
void pop(int *pos){
(*pos)--;
}
int main(){
int *myArray, pos = 0, i, sizeOfArray = 5;
myArray = (int *)malloc(sizeof(int)*sizeOfArray);
*(myArray + pos)= pos;
pos++;
*(myArray + pos) = pos;
pos++;
*(myArray + pos) = pos;
pos++;
//for(i = 0;i < pos;i++)
//printf("%d\n",*(myArray+i));
push(&pos, myArray, &sizeOfArray);
push(&pos, myArray, &sizeOfArray);
push(&pos, myArray, &sizeOfArray);
push(&pos, myArray, &sizeOfArray);
//pop(&pos);
//pop(&pos);
//pop(&pos);
for(i = 0;i<pos;i++)
printf("** %d\n",*(myArray+i));
return 0;
}
Now, the error has changed - which, perhaps, is an indication that there is something wrong with the approach - and it reads:
I should get:
** 0
** 1
** 2
** 3
** 4
** 5
** 6
Instead, I get:
** 0
** 0
** 2
** 3
** 4
** 5
** 6
Why? I only get this when I un-comment the printf in the middle.
Thank you for your help.