Re: Segmentation fault!



Paminu wrote:

I have a wierd problem.

In my main function I print "test" as the first thing. But if I run
the call to node_alloc AFTER the printf call I get a segmentation
fault and test is not printed!

#include <stdlib.h>
#include <stdio.h>

typedef struct _node_t {
int num_kids;
void *content;
struct _node_t **kids; // Makes a pointer to a pointer of node_ts.
} node_t;

node_t *node_alloc(void *content, int num)
{
node_t *parent;
parent = malloc(sizeof(node_t));

You should test whether malloc() returns NULL.

parent->content = content;
parent->num_kids = num;
node_t *new_kids[num];
int i;

You're missing this line:

parent->kids = new_kids;

But then, you'd really want:

parent->kids = malloc(num * sizeof (node_t *));
if (parent->kids) ...

As `new_kids` will disappear after you exit the function.


// Initialize children to NULL.
for (i = 0; i < num; i++)
{
parent->kids[i]=NULL;

}
return parent;
}


int main(void)
{

printf("test");

If you don't terminate printf() with \n you may not get anything out.

node_t *root = node_alloc("Root",4);
return 0;
}


Only if I outcomment the call to node_alloc will it print "test"! Why
does it not print "test" and then afterwards give me the "Segmentation
Fault"?

It seems that the call to node_alloc is executed before the printf
call...

No, you just invoked the wrath of Undefined Behaviour, by trying to
access uninitialised pointers...

--
BR, Vladimir

What!? Me worry?
-- A.E. Newman

.



Relevant Pages

  • Re: Segmentation fault!
    ... the call to node_alloc AFTER the printf call I get a segmentation ... int num_kids; ... parent = malloc); ... If you don't terminate printf() with \n you may not get anything out. ...
    (comp.lang.c)
  • Re: Segmentation fault!
    ... the call to node_alloc AFTER the printf call I get a segmentation ... int num_kids; ... parent = malloc); ... If you don't terminate printf() with \n you may not get anything out. ...
    (comp.lang.c)
  • Re: Segmentation fault!
    ... the call to node_alloc AFTER the printf call I get a segmentation ... int num_kids; ... parent = malloc); ... If you don't terminate printf() with \n you may not get anything out. ...
    (comp.lang.c)
  • Re: Segmentation fault!
    ... int num_kids; ... parent = malloc); ... It seems that the call to node_alloc is executed before the printf call... ... Fault" is probably the result of not allocating space for the data ...
    (comp.lang.c)
  • Re: About sleep() in a child process
    ... While the printf() seems not to work at all. ... Parent: PID is 14181 ... int main{ ...
    (comp.unix.programmer)