-1

Can't figure out how to remove the error.please help in removing segmentation fault (core)

struct node
{
  int a;
  node * link;
}**u;

u = (struct node**) malloc( m * sizeof(struct node*) );

struct node *f = u[z-1];  // z is int

while(f->k!=x && f!=NULL)
{
  f = f->link;  
  count = count + 1;
}

if(f->k!=x )
{
  printf("-1");
}
else
{
  printf("%ld",count);
}
Jens
  • 8,423
  • 9
  • 58
  • 78
shubh
  • 11
  • 2
  • 1
    Run your code under a debugger and identify exactly where the code is failing. – Jonathon Reinhart Apr 27 '14 at 21:35
  • Also, [don't cast the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Jonathon Reinhart Apr 27 '14 at 21:36
  • until f=u[z-1] there is no problem, however in following lines problem possibly is present. tried not casting result of maaloc. it didn't worked. – shubh Apr 27 '14 at 21:41
  • 1
    Please post a more complete code snippet which would compile and link and run. In your code above, what's the value of `m` and `z`? Where do you initialize the links in each structure? All you do is allocate some memory which contains nothing but random bits. – Jens Apr 27 '14 at 21:45
  • 1
    You say not casting `malloc()` "didn't work". In what way didn't it work? Are you compiling C code with a C++ compiler? Or did you just forget to include ``? – Jonathan Leffler Apr 27 '14 at 21:56
  • You never allocate any of the pointers. And yeah, stop casting the result of `malloc` – Ed S. Apr 27 '14 at 21:58
  • @shubh, It doesn't appear that 'k' is an element of 'struct node *f'? – Mahonri Moriancumer Apr 27 '14 at 22:07
  • Also, the 'struct node' definition contains an element called 'link' of type 'node' pointer. Can you supply the definition of the 'node' type (in the context of the 'struct node' definition you supplied)? – Mahonri Moriancumer Apr 27 '14 at 22:11

1 Answers1

1

You're allocating space for the pointers:

u = malloc( m * sizeof(struct node*) );

but the pointers themselves are uninitialized. They could literally be pointing anywhere.

So:

struct node *f = u[z-1];  // z is int

means "make f point to some random point in memory". You'll want to allocate the nodes.

u = malloc( m * sizeof(struct node*) );

for ( i = 0; i < m; ++i )
  u[i] = malloc( sizeof( struct node ) );

// Now this means something

struct node *f = u[ z - 1 ];
Paul Roub
  • 36,322
  • 27
  • 84
  • 93