Assignment between pointers work only inside main, not in procedure body - c

I'm getting a segmentation fault error, if I try to make a copy between pointers to a struct, inside a procedure body.
If I instead, make the copy between pointers within the main() body, everything works correctly.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *father, *lchild, *rchild;
} node;
typedef struct node Node;
// Prototypes
Node* insertRoot(int val, Node* N);
int main(){
Node * A = NULL;
Node * b = insertRoot(10, A);
//A = b; // If I do the assignment here it works correctly.
printf("A->value = %d \n\n" , A->value); //Segmentation fault!
return 0;
}
Node* insertRoot(int val, Node* N){
Node* temp = malloc(sizeof(Node));
temp->value = val;
temp->father = NULL;
temp->lchild = NULL;
temp->rchild = NULL;
N = temp; // If I do the assignment here instead, it won't work.
return temp;
};

You are not assigning any value to A inside insertRoot, you are assigning to N which is a copy of A. That leaves the value A=NULL unchanged.

Related

why does it show segmentation error in my code?

this is the code for printing the two strings together but whenever I try to run it, there's a segmentation error but it compiles without any error, can anyone help?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char *data; //string data in this node
struct node *next; //next node or NULL if none
} Node;
void print(Node *head); //function prototype print
Node *push_node(Node x, Node *strlist);
int main ()
{
Node node1;
Node node2;
Node *list = NULL;
strcpy(node1.data, "world");
push_node(node1, list);
strcpy(node2.data, "hello");
push_node(node2, list);
print(list);
return 0;
}
void print(Node *head)
{
Node *p = head;
while (p != NULL)
{
printf("%s", p->data);
p = p->next;
}
}
Node *push_node(Node x, Node *strlist)
{
x.next= strlist;
return &x;
}
You declared two objects of the type Node
Node node1;
Node node2;
data members of which are not initialized. That is the pointers data of the objects have indeterminate values.
So calling the function strcpy
strcpy(node1.data, "world");
strcpy(node2.data, "hello");
results in undefined behavior.
Also the pointer list is not being changed within the program. It is always equal to NULL as it was initialized. So calling the function print does not make a sense.
To make your code at least working you need to make the following changes.
Node *push_node(Node *x, Node *strlist);
//...
node1.data = "world";
list = push_node( &node1, list);
node2.data = "hello";
list = push_node( &node2, list);
print(list);
//...
Node *push_node(Node *x, Node *strlist)
{
x->next= strlist;
return x;
}

Does array initialize memory in c? [duplicate]

This question already has answers here:
initial value of int array in C
(10 answers)
Closed 2 years ago.
Having this linked list:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
typedef struct node node_t;
void printlist(const node_t*);
node_t *create_node(int);
int main(void){
int values[3] = {1,2,3};
node_t *nodes[3];
for(int i =0; i<3 ; i++)
{
nodes[i] = create_node(values[i]);
if(i!=2)
nodes[i]->next = nodes[i+1]; //HERE, can I assign next (un)initialized node?
}
node_t *header = nodes[0];
printlist(header);
}
void printlist(const node_t* header){
for(const node_t *i = header; i; i=i->next)
printf("value is %i\n",i->value);
}
node_t *create_node(int value){
node_t *new = malloc(sizeof(node_t));
new->value=value;
new->next = 0;
return new;
}
Which gives:
value is 1
value is 29590344
Command terminated
As I can see from output, the first node (header), does not have assign next struct member, which should happened from the loop. But I am assigning the next (pointer to new node) to an (un)initialized member from array (of pointer to nodes). I expect a initilization of array should also initilize a memory, when it has size. But does it? If so, then I do not understand why the assignment does not work, otherwise I understand and have to implement other loop. Thanks for answers.
Your code does not create the dynamic list as you have an array of 3 nodes. next is not needed.
You probably want something like this.
/* you need to check if memory allocation was successful */
#include <stdlib.h>
#include <stdio.h>
typedef struct node {
int value;
struct node *next;
} node_t;
void printlist(const node_t*);
node_t *append_node(node_t *, int);
int main()
{
node_t *head = NULL, *parent = head;
for(int x = 0; x < 10; x++)
if(!head)
{
head = append_node(NULL, x);
parent = head;
}
else
{
parent = append_node(parent, x);
}
printlist(head);
}
void printlist(const node_t* head){
while(head)
{
printf("value is %i\n",head->value);
head = head -> next;
}
}
node_t *append_node(node_t *parent, int value){
node_t *new = malloc(sizeof(*new));
new->value=value;
new->next = NULL;
if(parent) parent -> next = new;
return new;
}

Issue inserting node in linked list

I am practicing creating a link list, but encountered a problem when trying to insert an item to the front of the list. The code in my insert function works properly if I put it within main, but not when run separately as a function.
I am using a pointer as a argument in the function so I don't understand why the value in my print statement isn't changing to 100 which should be at the front of the linked list using the insert function (When I run the function 61 is printed, I am aiming for 100 to be printed).
Thanks for the help!
#include <stdio.h>
#include <stdlib.h>
typedef struct node *nodePtr;
typedef struct node node;
struct node {
int value;
nodePtr next;
};
node insert(node *first, int value)
{
nodePtr temp;
temp = malloc(sizeof(node));
temp->value = value;
temp->next = first;
first = temp;
}
int main()
{
nodePtr first;
first = malloc(sizeof(node));
first->value = 61;
first->next = NULL;
insert(first, 100);
printf("%d", first->value);
}
your passing a pointer to the node as a argument to the function and changing the value of formal parameter does not change the value of the actual parameter do this it should work.
enter code here
#include <stdio.h>
#include <stdlib.h>
typedef struct node *nodePtr;
typedef struct node node;
struct node {
int value;
nodePtr next;
};
void insert(node **first, int value)
{
nodePtr temp;
temp = malloc(sizeof(node));
temp->value = value;
temp->next = *first;
*first = temp;
}
int main()
{
nodePtr first;
first = malloc(sizeof(node));
first->value = 61;
first->next = NULL;
insert(&first, 100);
printf("%d",first->value);
}
You have passed a pointer to function insert() and stored it in a variable first whose scope is local to function insert(). Now you have
updated pointer first in function insert().
When you will return to main() function updated value of pointer next is lost that is why you are getting unexpected result while printing value in main().
To summarise:
first = malloc(sizeof(node)); // let's say first is p1
...
insert(first, 100); // first is P1
....
node insert(node *first, int value) // first is p1
....
tmp = malloc(sizeof(node)); // let's say tmp is p2
first = temp; // Now first has become p2 but its scope is local to insert()
....
printf("%d", first->value); // first is still p1 here
Solution
node* insert(node *first, int value)
{
nodePtr temp;
temp = malloc(sizeof(node));
temp->value = value;
temp->next = first;
first = temp;
return first;
}
int main()
{
nodePtr first;
first = malloc(sizeof(node));
first->value = 61;
first->next = NULL;
first = insert(first, 100);
printf("%d", first->value);
return 0;
}

How to print Linked List in C?

#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
void CreateList(LinkedList N, int n)
{
N = (LinkedList)malloc(sizeof(Node));
N->next = NULL;
LinkedList new = N;
Node *p;
for (int i = 0; i < n; ++i) {
p = (Node *)malloc(sizeof(Node));
scanf("%d", &(p->data));
new->next = p;
new = p;
}
new->next = NULL;
}
int main()
{
LinkedList list;
CreateList(list, 20);
printf("%d", list->data);
return 0;
}
As you can see, I want to create a linkedlist and make it a function.
But when I "printf" linkedlist's data, it can't appear what i want.
Can you help me?
The direct problem, as M. Oehm notes, is that you pass the list object to the create function. The create function creates the list, but because the list object is not returned to main, main cannot see the list. To achieve what you want, do:
In main, declare the list as:
LinkedList *N; // a pointer
declare create as:
void CreateList(LinkedList **N, int n) // address of a pointer that receives the value
and dereference it in create:
*N = malloc(sizeof(Node)); // assign the value to the pointer in main
and now call it from main as:
CreateList(&N, 20); // pass the address of the pointer
I further note that you pass create an int, the number of elements in the list, but a list is typically made for an unknown number of elements. So you should read until end-of-file.
(All other required modifications in create I leave to you.)
Thank you all!! I solved this problem, and this is my code.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void create(Node* *head, int n)
{
*head = malloc(sizeof(Node));
(*head)->next = NULL;
Node* new = *head;
Node* p;
for (int i = 0; i < n; ++i) {
p = malloc(sizeof(Node));
scanf("%d", &(p->data));
new->next = p;
new = p;
}
}
int main()
{
Node* list;
create(&list,20);
printf("%d", ((list->next)->next)->data); //for test
return 0;
}

Segment Fault when initialization multiple nodes

I am working on a binary search tree in C. I am having a problem with initializing multiple nodes.
typedef struct Node Node;
struct Node{
int* data;
Node* leftChild;
Node* rightChild;
Node* parent;
};
void initNode(Node* node, int* data){
node->data = data;
node->leftChild = NULL;
node->rightChild = NULL;
node->parent = NULL;
}
The above code seems to work fine when calling initNode() only once. But if I attempt to make the second call I get a segment fault.
My main looks like this:
int main(){
Node* node;
Node* node2;
int a = 12;
int b = 15;
initNode(node, &a);
printf("%i \n", *node->data);
}
This works. However if I do this:
int main(){
Node* node;
Node* node2;
int a = 12;
int b = 15;
initNode(node, &a);
initNode(node2, &b);
printf("%i \n", *node->data);
}
I get a segment fault. Any ideas why this behavior is happening?
You have not allocated memory for both node or node2. Since both the pointers are allocated on stack they will have junk values. Its just accident that the first program passes at all.
This function:
void initNode(Node* node, int* data){
node->data = data;
node->leftChild = NULL;
node->rightChild = NULL;
node->parent = NULL;
}
expects node to have already been initialized.
You don't do that in either of your programs. Dereferencing a pointer that hasn't been assigned is undefined behavior. It's just by chance that it worked in your first program. Who knows what memory you're overwriting.
You need to initialize node and node2.
Node* node = malloc(sizeof*node);
Node* node2 = malloc(sizeof*node2);
Just remember to free them once you're finished with them.
A much cleaner solution is to allocate the Nodes on the stack, so you don't have to worry about calling free.
int main(void) { /* use a valid signature for main() */
Node node; /* just a straight up Node (not a pointer) */
Node node2;
int a = 12;
int b = 15;
initNode(&node, &a); /* use address of operator on nodes */
initNode(&node2, &b);
printf("%i \n", *node->data);
}

Resources