Re: Segmentation fault!
- From: "Rod Pemberton" <do_not_have@xxxxxxxxxxxxxxxxxxx>
- Date: Sat, 11 Feb 2006 14:10:34 -0500
"Vladimir S. Oka" <novine@xxxxxxxxxxxxxxx> wrote in message
news:dskqvf$bc1$1@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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;
*** kids is an array of pointers to _node_t, correct? Wouldn't kids be
better defined like so:
struct _node_t *(kids[]);
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;
*** He's changing the type of content from 'const char *' to 'void *'.
Also, if he doesn't allocate space for content, he'll continue to get
segmentation faults.
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;
}
I think his program should look more like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _node_t
{
int num_kids;
char *content;
struct _node_t *(kids[]);
} node_t;
void node_alloc(node_t *parent, char *content, int num)
{
int i;
parent = malloc(sizeof(node_t));
parent->num_kids = num;
parent->content = malloc(strlen(content));
strcpy(parent->content,content);
parent->kids[0] = malloc(sizeof(node_t *)*num);
// Initialize children to NULL.
for(i=0;i<num;i++)
parent->kids[i]=NULL;
}
int main(void)
{
node_t *root=NULL,*next=NULL;
char temp[32];
printf("test\n");
sprintf(temp,"%s","Root");
node_alloc(root,temp,4);
sprintf(temp,"%s","First");
node_alloc(next,temp,3);
root->kids[0]=next;
sprintf(temp,"%s","Second");
node_alloc(next,temp,2);
root->kids[1]=next;
return 0;
}
Rod Pemberton
.
- Follow-Ups:
- Re: Segmentation fault!
- From: stathis gotsis
- Re: Segmentation fault!
- From: Chris Torek
- Re: Segmentation fault!
- References:
- Segmentation fault!
- From: Paminu
- Re: Segmentation fault!
- From: Vladimir S. Oka
- Segmentation fault!
- Prev by Date: www.bornwitit.com
- Next by Date: Re: Segmentation fault!
- Previous by thread: Re: Segmentation fault!
- Next by thread: Re: Segmentation fault!
- Index(es):
Relevant Pages
|