an*******@coolgroups.com wrote:
I am getting Segmentation fault, core dump error from the
following program. The program is a stack implementation
with push and pop functions(at present only push is
implemented). I dont know where i am erring. Here is the
program:
#include<stdio.h>
int main()
{
int * stackptr;
void push(int **pushint, int i);
/*Memeory allocation for stack*/
stackptr=(int *)malloc(100 * sizeof(int));
You're missing an include of <stdlib.h> and you're keeping the
compiler from complaing about that by casting the return value
of malloc() (which usually doesn't make too much sense anyway).
push(&stackptr, 10);
printf("The stack is %d\n",*stackptr);
It's probably crashing here. When you look at what value
'stackptr' has you will find that it's 10 and not the
address you got from malloc() anymore.
return 0;
}
void push(int **stackptr, int i)
{
*stackptr=i;
Here you overwrite the address the 'stackptr' pointer from main()
is pointing to (i.e. the address of the memory you allocated in
main()) instead of writing the integer into the memory at that
address. Your compiler should warn you about that (some warning
about a type mismatch in the assignment) Try again with
**stackptr=i;
The question of course is why you pass the address of the pointer
to the function if you don't want to change that address...
Regards, Jens
--
\ Jens Thoms Toerring ___
Je***********@physik.fu-berlin.de
\__________________________
http://www.toerring.de