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

typedef struct node
{
    char *arr;
    struct node *next;
} node;

int main()
{
    char *word = (char *)malloc(sizeof(char) * 20);
    strcpy(word, "jon jones");

    node *sentence;
    sentence->arr = word;         //Problem here
    printf("%s", sentence->arr);

    return 0;
}

I am trying to dynamically allocate a character array. Put a string in there and then make the data element of the node point to the character array. When I run the program I get a segmentation fault. I suspect it is from the line that I labeled above. What I do not understand is, I made sentence->arr point to the first element of the word array. Why would it crash like that? Thanks in advance.

jdarthenay
  • 3,062
  • 1
  • 15
  • 20
John Doe
  • 17
  • 1
  • 5
  • 2
    Note off topic:There is [no need](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) to cast a result of `malloc` – red0ct Apr 23 '16 at 17:24

4 Answers4

0
node *sentence;
sentence->arr = word;         //Problem here

Pointer sentence declared but it is not initialized and dereference so it causes undefined behavior.

Allocate memory before dereferencing it -

node *sentence;
sentence=malloc(sizeof(*sentence));

Also if you want to make nodes then use strcpyinstead of this -

sentence->arr = word;       // but allocate memory to `arr` before copying
ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

You forgot to initialize your sentence variable.

Following works for me

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

typedef struct node
{
    char *arr;
    struct node *next;
}node;

int main()
{
    char *word = (char *)malloc(sizeof(char) * 20);
    strcpy(word, "jon jones");

    node *sentence = (node*)malloc(sizeof(node)); // Initialize node area
    sentence->arr = word; 
    printf("%s", sentence->arr);

    return 0;
}
Mads Buch
  • 344
  • 2
  • 10
0

You are using a pointer to node but this node has not been allocated. Use : node sentence; sentence.arr = word; printf("%s", sentence.arr);

It should be better. You can also use gdb for finding out which line causes the fault.

SeB
  • 1,159
  • 6
  • 17
  • You should also free the dynamically allocated memory when it is no longer useful. – SeB Apr 23 '16 at 17:27
  • Yes, I am aware of this and know how to do it. I was working on a much larger program but I couldnt get past this hump for awhile so I tried making a smaller program to understand the mechanics of why "this" or "that" wasnt working. Thank you for your time and help – John Doe Apr 23 '16 at 17:31
0

Either alloc memory for node as you did for word or use a struct instead of struct pointer.

node *sentence;
sentence = (node*)malloc(sizeof(node));
sentence->arr = word;         
printf("%s", sentence->arr);

or

node sentence;
sentence.arr = word;         
printf("%s", sentence->arr);
padfoot
  • 811
  • 7
  • 16