Re: Segmentation fault!
- From: "Vladimir S. Oka" <novine@xxxxxxxxxxxxxxx>
- Date: Sat, 11 Feb 2006 14:05:36 +0000 (UTC)
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
.
- Follow-Ups:
- Re: Segmentation fault!
- From: Rod Pemberton
- Re: Segmentation fault!
- From: Paminu
- Re: Segmentation fault!
- References:
- Segmentation fault!
- From: Paminu
- Segmentation fault!
- Prev by Date: Re: a great deal
- Next by Date: Re: How can I write highly optimized C code for reading and writing?
- Previous by thread: Segmentation fault!
- Next by thread: Re: Segmentation fault!
- Index(es):
Relevant Pages
|