malloc problem

S

sabads

Hello everyone:
I have a problem like this :
typedef struct node {
char *data;
struct node *next;
}lnode;
when I allocate space for node p : p = (lnode *)malloc(sizeof(struct
node));
it happened display : Segmentation fault.
I think it will be problem the 'char *data' is not enough
initialization and compiler
cann't know the size precisely. so the space allocated is not satisfy
with the input data ??
so what i should do for this ?
 
H

hari4063

It will be better to provide little source code. but I think that You do
not allocate memory for string. So, after creating new node with malloc (p
= (lnode *)malloc(sizeof(structnode));) You must allocate p->data:

p->data = (char*)malloc(strlen(str)+1);
strcpy(p->data, str);

Best,
Zaharije Pasalic
 
N

Nitin

Verify whether stdlib.h is included.Non inclusion of this may result in
segmentation fault whenever malloc is called on some flavours of unix
 
T

Thomas Matthews

sabads said:
Hello everyone:
I have a problem like this :
typedef struct node {
char *data;
struct node *next;
}lnode;
when I allocate space for node p : p = (lnode *)malloc(sizeof(struct
node));
it happened display : Segmentation fault.
I think it will be problem the 'char *data' is not enough
initialization and compiler
cann't know the size precisely. so the space allocated is not satisfy
with the input data ??
so what i should do for this ?

First off, include the stdlib.h header file, that way
you don't need to cast the result of malloc:
#include <stdlib.h>

To allocate a node structure:
struct node * Allocate_Node()
{
struct node * new_node;
new_node = malloc(sizeof(struct node));
if (new_node)
{
new_node->data = 0;
new_node->next = 0;
}
return new_node;
}


To allocate characters, during run-time, for the
data field of the node:
struct node * new_node;

new_node = Allocate_Node();
if (new_node)
{
new_node->data = malloc(/* number of characters + 1 */);
}


--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
 
S

sabads

Thank all of your reples !
////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node {
char *data;
struct node *next;
}lnode;

int main()
{
int i = 0;
lnode *p,*head = NULL;
char *str;

printf("input string: \n");
for (i = 1; i < 5; i++) {
scanf("%s",str);
p = (lnode *)malloc(sizeof(lnode));
p->data = (char *)malloc(strlen(str)+1);
strcpy(p->data,str);
p->next = head;
head = p;
}
p = head;
while (p != NULL) {
printf("%s ",p->data);
p = p->next;
}
return 0;
}
this is my test code but still Segmentation fault. i don't know what's
wrong ?
 
D

David Resnick

sabads said:
Thank all of your reples !
////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node {
char *data;
struct node *next;
}lnode;

int main()
{
int i = 0;
lnode *p,*head = NULL;
char *str;

printf("input string: \n");
for (i = 1; i < 5; i++) {
scanf("%s",str);

str is an uninitialized pointer. It likely doesn't point to somewhere
you can write. This should be easy to debug, you should become
comfortable using whatever tools you have available to help identify
such things (e.g. on linux using gdb to step through code /examine core
or valgrind). You could repair this by declaring char
str[MAX_LINE_LENGTH]; and by telling scanf not to read more than
MAX_LINE_LENGTH characters into it.

-David
 
A

Al Bowers

sabads said:
Thank all of your reples !
////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node {
char *data;
struct node *next;
}lnode;

int main()
{
int i = 0;
lnode *p,*head = NULL;
char *str;

printf("input string: \n");
for (i = 1; i < 5; i++) {
scanf("%s",str);
p = (lnode *)malloc(sizeof(lnode));
p->data = (char *)malloc(strlen(str)+1);
strcpy(p->data,str);
p->next = head;
head = p;
}
p = head;
while (p != NULL) {
printf("%s ",p->data);
p = p->next;
}
return 0;
}
this is my test code but still Segmentation fault. i don't know what's
wrong ?

You are attempting to input the string data into a char *str
which has no space allocated for it. You will need to first
allocate storage for the data and then get the data. You
could write a function that does this, see function fgetline
below.

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

typedef struct node {
char *data;
struct node *next;
}lnode;

int AddNode(lnode **head, const char *data);
char *fgetline(FILE *fp);
void PrintNodes(lnode *head);
void FreeNodes(lnode **head);

int main(void)
{
int i = 0;
lnode *head = NULL;
char *str;

for (i = 0; i < 5; i++)
{
printf("Input String #%d: ",i+1);
fflush(stdout);
str = fgetline(stdin);
if(str != NULL) AddNode(&head,str);
}
puts("\n\tThe Node data is:");
PrintNodes(head);
FreeNodes(&head);
return 0;
}

char *fgetline(FILE *fp)
{
char *s, *tmp;
const size_t BLOCK = 32;
size_t count;
int ch;

for(count = 0, s = NULL;
(ch = fgetc(fp)) != EOF && ch != '\n';count++)
{
if(count%BLOCK == 0)
{
tmp = realloc(s,count+BLOCK+1);
if(tmp == NULL)
{
free(s);
return NULL;
}
s = tmp;
}
s[count] = ch;
}
if(s) s[count] = '\0';
return s;
}

int AddNode(lnode **head, const char *data)
{
lnode *tmp;

if((tmp = malloc(sizeof *tmp)) == NULL)
return 0;
tmp->data = (char *)data;
tmp->next = *head;
*head = tmp;
return 1;
}

void PrintNodes(lnode *head)
{
for( ; head; head = head->next)
puts(head->data);
return;
}

void FreeNodes(lnode **head)
{
lnode *tmp;

for( ; *head; *head = tmp)
{
tmp = (*head)->next;
free((*head)->data);
free(*head);
}
return;
}
 
M

Martin Ambuhl

sabads said:
int main()
{
int i = 0;
lnode *p,*head = NULL;
char *str;

printf("input string: \n");
for (i = 1; i < 5; i++) {
scanf("%s",str);

This is the segmentation fault. 'str' points to your toaster, which is
a read-only device.
 
M

Michael Wojcik

Various people have noted your major error (writing through an
uninitialized pointer), but it's worth pointing out some minor
ones and style issues:
int main()

This should be one of:

int main(void)
int main(int argc, char **argv)

(the parameter names in the second form are unimportant) for a
program running under a hosted implementation.
printf("input string: \n");

The space before the newline is probably not useful, and many
people prefer puts (or fputs) to printf (and fprintf) if no
formatting is being done. Note that puts adds a newline
automatically, so in this case you'd have:

puts("input string:");

Use fputs if you don't want a newline.
p = (lnode *)malloc(sizeof(lnode));

Unless you're writing C++, the cast is unnecessary and can
conceal the error of forgetting to include stdlib.h. If you
use sizeof on the dereferenced pointer rather than a type
name, then you avoid a possible error if the type of the
object pointed to by p changes. Thus:

p = malloc(sizeof *p);

Note this is also more concise and easier to read.

You've neglected to check if malloc succeeded. Even in little
test programs I believe in making that check; prototype code
has a way of getting into production code.

If you write a skeleton test program for prototyping, and
include in it a function that, say, displays a message and
calls "exit(EXIT_FAILURE)", then you can use that if a malloc
fails with minimal effort on your part.
p->data = (char *)malloc(strlen(str)+1);

Similarly here:

p->data = malloc(strlen(str)+1);
if (! p->data) ...
 
R

Richard Bos

This should be one of:

int main(void)
int main(int argc, char **argv)

(the parameter names in the second form are unimportant) for a
program running under a hosted implementation.

Actually, it needn't. It's better style, but neither C89 nor C99
requires the void or parameters. (C99 requires the explicit int, though,
which C89 did not.)

Richard
 
M

Michael Wojcik

Actually, it needn't. It's better style, but neither C89 nor C99
requires the void or parameters. (C99 requires the explicit int, though,
which C89 did not.)

That's not how I read 9899-1990 5.1.2.2.1:

[main] can be defined with no parameters:

int main(void) { /*...*/ }

or with two parameters...

6.7.1 certainly makes the parameter list optional in general, but
ISTM that a conforming implementation could require one of the two
forms for main described in 5.1.2.2.1. I don't see anything that
requires an implementation to accept "int main()". Thus "int main()"
is non-portable (which is what I meant by "should be" above).

But I'm prepared to be enlightened.
 
M

Mark McIntyre

That's not how I read 9899-1990 5.1.2.2.1:

int main(void) { /*...*/ }

this is totally equivalent to
int main() {/*...*/}

in a function definition.
6.7.1 certainly makes the parameter list optional in general, but
ISTM that a conforming implementation could require one of the two
forms for main described in 5.1.2.2.1. I don't see anything that
requires an implementation to accept "int main()".

The grammar of the language requires it.
 
K

Keith Thompson

Mark McIntyre said:
this is totally equivalent to
int main() {/*...*/}

in a function definition.

I think you're right. C99 6.7.5.3p14 says:

[...] An empty list in a function declarator that is part of a
definition of that function specifies that the function has no
parameters. The empty list in a function declarator that is not
part of a definition of that function specifies that no
information about the number or types of the parameters is
supplied.

I had been thinking that int main() would allow mismatched arguments
on a recursive call to main, but the above shows that I was mistaken.
I just tried a test case on several compilers, and most of them appear
to get this wrong as well, issuing no diagnostics for the following:

#include <stdio.h>

void foo()
{
printf("In foo\n");
}

int main()
{
foo();
foo(42);
return 0;
}
 
P

pete

Keith said:
Mark McIntyre said:
this is totally equivalent to
int main() {/*...*/}

in a function definition.

I think you're right. C99 6.7.5.3p14 says:

[...] An empty list in a function declarator that is part of a
definition of that function specifies that the function has no
parameters. The empty list in a function declarator that is not
part of a definition of that function specifies that no
information about the number or types of the parameters is
supplied.

I had been thinking that int main() would allow mismatched arguments
on a recursive call to main, but the above shows that I was mistaken.
I just tried a test case on several compilers, and most of them appear
to get this wrong as well, issuing no diagnostics for the following:

#include <stdio.h>

void foo()
{
printf("In foo\n");
}

int main()
{
foo();
foo(42);
return 0;
}

Old style function types don't include the parameter types.
int main() is old style.
int main(void) is more better.
 
K

Keith Thompson

pete said:
Old style function types don't include the parameter types.
int main() is old style.
int main(void) is more better.

It appears that in the context of a function *definition*, int main()
is exactly equivalent to int main(void).

Nevertheless, I consider int main(void) to be better style. It's more
explicit, it avoid confusion with the use of int main() in function
*declarations* (which is different from int main(void)), and, as I
recently discovered, some compilers don't catch certain errors with ()
that they do catch with (void).
 
M

Michael Wojcik

this is totally equivalent to
int main() {/*...*/}

in a function definition.

Indeed it is. However, I'm not talking about "a function definition";
I'm talking about the two forms for main specified by 5.1.2.2.1.
The grammar of the language requires it.

It does no such thing. There are many, many things permitted by the
grammar but disallowed in conforming code, such as passing a null
pointer to strlen. The grammar permits all sorts of declarations
for main; 5.1.2.2.1 specifically restricts the conforming ones (in
a hosted implementation) to two.

--
Michael Wojcik (e-mail address removed)

Unlikely predition o' the day:
Eventually, every programmer will have to write a Java or distributed
object program.
-- Orfali and Harkey, _Client / Server Programming with Java and CORBA_
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,431
Latest member
ElyseG3173

Latest Threads

Top