UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » segment error

#1 2007-11-03 10:01 AM

zhn636
Member
Registered: 2007-04-24
Posts: 146

Re: segment error

I write a program ,the code is:

1 #include <stdio.h>
      2 typedef struct
      3 {
      4 int stack[4];
      5 int top;
      6 }stack;
      7 void init( stack *s)
      8 {
      9 s->top=-1;
     10 }
     11 int main()
     12 {
     13 int i,x=4;
     14 stack *s;
     15 init(s);
     16 printf("%d\n",s->top);
     17 s->top++;
     18 s->stack[s->top]=x;
     19 printf("%d\t",s->top);
     20 printf("%d\n",s->stack[s->top]);
     21 printf("\n");
     22 }

when I execute it ,it appear segment error.
how can I modify this program?
I am doubt what is the matter.

Offline

#2 2007-11-03 06:49 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: segment error

Your problem is you simply declare "s" as a pointer to one of these structs, yet
never allocate any memory for it...  So, you just have a bogus uninitialized pointer
value, pointing to random junk...

You basically have 2 choices: 1) Declare it as simply "stack s;", then pass "&s" to any
functions wanting the pointer, and change your "->"s in main() to simple "."s...  Or, 2)
Add an "s = malloc (sizeof (stack));" prior to use of it, if you want to stick with the
"stack *s;" declaration...

Offline

  • Index
  • » C
  • » segment error

Board footer

Powered by FluxBB