Segmentation fault with char array member of struct using strcpy() - c

I have a struct TREE defined this way:
typedef struct TREE {
NODE *head;
} TREE;
and a struct NODE defined as:
typedef struct NODE {
char boss[30];
char name[30];
struct NODE *firstChild;
struct NODE *secondChild;
struct NODE *thirdChild;
struct NODE *fourthChild;
} NODE;
In my main, I have:
TREE companyStructure;
TREE *treeptr;
treeptr = &companyStructure;
strcpy(treeptr->head->name, "Ben");
But this gives me a segmentation fault. Can someone help me explain why this is the case? Is there some memory management that I'm not doing that I need to be doing?

Till,
treeptr = &companyStructure;
Things look good. But then considering the fact that you have
NODE *head;
you need to allocate memory for head. So most likely you've missed
treeptr->head = malloc(sizeof *treeptr->head);
before doing
strcpy(treeptr->head->name, "Ben");
Also, check [ this ] on why should you use strncat instead of strcpy.

Related

I cannot typedef a pointer to structure that has already been typedef-ed

I am a bit comfused about the row of these declarations. I want to make a linked-list for my program but for some reason it keeps putting error when I try to compile it. Basically this will be my main node model and I also have another struct after it (WITHOUT TYPEDEF) for my list. Which compiles just fine. I don't know what's wrong.
I have already tried to put the typedef over the struct student.
typedef struct
{
char name[50];
int id;
node next;
}student;
typedef student* node;
typedef struct listR* list;
struct listR
{
node head,tail;
int size;
};
error:
unknown type name 'node'
warning:
initialization make pointer from integer without a cast
The compiler doesn't know what a node is, because you create the node type after creating the structure.
You can do either :
typedef struct node node;
struct node
{
char name[50];
int id;
node* next;
};
To tell the compiler what a node is,
Or
typedef struct node {
char name[50];
int id;
struct node* next;
} node;
I would use this:
struct Node
{
struct Node *next;
struct Node *prev;
};
But then I happen to be one of those who does not like typedeffing structs without a good reason. Read more here: https://stackoverflow.com/a/54752982/6699433

C programming trie tree insert

I just started programming and have a beginner question,I am writing a trie insert function that insert a string into the trie tree. But when I add a string with more than two characters I'm getting heap buffer overflow. Here is my insert function:
struct node* insert(struct node *root,char *c){
int i=0;
struct node *temp=root;
while(c[i]){
int index=c[i]-'a';
//New Node
struct node *n=malloc(sizeof(*n));
n=malloc(sizeof(struct node));
temp->child[index]=n;
i++;
temp=temp->child[index];
}
return root;
};
The definition of the tree node
struct node
{
int isword;
int prefix;
int occurrence;
int leaf;
struct node * child[26];
};
and How I called them
char *c=malloc(3*sizeof(char));
c[0]='a';
c[1]='d';
c[2]='e';
struct node *root=malloc(sizeof(*root));
root=malloc(sizeof(struct node));
insert(root,c);
I think it's how I allocate space in the insert function for new node that went wrong, but I'm not sure what's the proper way to avoid heap buffer overflow, any advice please?
c is not ending with nul. So c[i] is undefined if i>=3(maybe coredump because access invalid memory address). while(c[i]) may run more than 3 times. This maybe the point.
char *c=malloc(3*sizeof(char));
c[0]='a';
c[1]='d';
c[2]='e';
btw, code below will cause memory leak:
struct node *root=malloc(sizeof(*root));
root=malloc(sizeof(struct node));

Build a general tree with C (use a linkedlist to hold the children)

Try to build a tree in C. The children has to be contained in a linkedlist. But when I use "struct listNode*" in the definition of struct treeNode, listNode is not declared yet. So is there any way to declare this first? Or anyway to get around this? Thanks!
/*** Build a tree ***/
typedef struct treeNode {
char* target;
char* commands;
struct listNode* children;
} tNode;
/*** Build a linkedlist ***/
typedef struct listNode {
struct treeNode dependency;
struct listNode* next;
} lNode;
Use what's called forward declaration. So your code should look like this
/*** Build a tree ***/
struct listNode;
typedef struct treeNode {
char* target;
char* commands;
struct listNode* children;
} tNode;
/*** Build a linkedlist ***/
typedef struct listNode {
struct treeNode dependency;
struct listNode* next;
} lNode;
Prepend the following to your snippet
struct listNode;
This is called a forward declaration.
The struct is not defined at this point, but the name is known, which is sufficient as you only want to reference it (with a pointer), not include it (which would require knowledge of its size).
Note that the restriction that you can only use pointers on yet-to-be-defined types actually makes sense: It makes
struct A {
struct B b;
int a;
};
struct B {
struct A a; /* Uh, what's that? struct B contains struct A
* which contains struct B... Now what's the size
* of either of these structs? */
};
an invalid construct (because it prevents circular dependencies).

Allocating space to a node pointer

I am currently attempting to use a doubly linked list to sort some data. I am having trouble creating a new node with the given data. Below was the code given to me:
#ifndef LIST_H_
#define List_H_
#define MAX_SYMBOL_LENGTH 7
struct order {
int id;
char symbol[MAX_SYMBOL_LENGTH];
char side;
int quantity;
double price;
};
typedef struct order* OrderPtr;
typedef struct onode* NodePtr;
struct onode {
OrderPtr data;
NodePtr next;
NodePtr prev;
};
This is the code that I have written using list.h as a header.
Here is the code that seemingly keeps crashing:
#include "list.h"
NodePtr newNode(OrderPtr data){
NodePtr node = (NodePtr)malloc(sizeof(NodePtr));
//node->data = (NodePtr)malloc(sizeof(OrderPtr));
//*node->data = *data;
node->data = data;//This is the one I am having problems with
node->next = NULL;
node->prev = NULL;
return node;
}
It compiles fine but when I try and submit it to an online grader it says that it does not work.
Here is my thought process,
create memory for NodePtr.
create memory for NodePtr->data.
and then assign the values of data passed from the function to the values in Node->Ptr.
But I do not know how to allocate memory for NodePtr->data.
NodePtr node = (NodePtr)malloc(sizeof(NodePtr));
Isn't doing what you are thinking. It's allocate space to hold a pointer same as sizeof(int*), it's 4 bytes on 32-bit machine, usually.
You need to do NodePtr node = malloc(sizeof(struct onode)); instead of.
data member should be result to a malloc(sizeof(struct order));
Also, don't cast result value from a malloc() call.
NodePtr is a pointer to a node and not the node itself. You're only allocating enough memory for a pointer and not all the members of the onode structure. You'll want to call malloc with sizeof(struct onode).

What is the purpose of the first "node" in the declaration: "typedef struct node { - - - } Node;"?

I am studying code examples from my professor in order to become better acquainted with linked data structures.
In our linked-list.c example the professor defines a type Node as follows:
typedef struct node {
int data;
struct node *next;
} Node;
What's the point of the lower case node? I was under the impression that you could just write, for example:
typedef struct {
int data;
struct node *next;
} Node;
and then use Node as its own type. Does it have something to do with the fact that if you don't include a lower case node then when the compiler is evaluating the code it will not be able to understand what is meant by "struct node *next"?
Take a look at this declaration:
struct node {
int data;
struct node *next;
};
typedef struct node Node;
This can be combined into a single statement (simplifying a declaration):
typedef struct node {
int data;
struct node *next;
} Node;
Does it have something to do with the fact that if you don't include a lower case node then when the compiler is evaluating the code it will not be able to understand what is meant by "struct node *next"?
Yes.
The node in struct node is the tag of the struct type. If you give the struct a tag, you can refer to that type from the moment on the tag is complete, so in
typedef struct node {
int data;
struct node *next;
} Node;
the struct node *next; declares a member next that is a pointer to the struct type being defined. The typedef name Node is not available before the ; ending the definition is reached.
If you omit the tag, you cannot refer to the type being defined in any way before the typedef is complete, so in
typedef struct {
int data;
struct node *next;
} Node;
the line struct node *next; declares a new, unrelated, incomplete struct type with the tag node that next points to.
That's valid, but nothing about struct node is known (unless it is defined somewhere else), so you can't use the next pointer without casting it to a pointer to a complete type everywhere (not quite everywhere, Node foo; foo.next = malloc(12); etc. would still work).
He is defining a temporary name for the node because he is using a well know technique to avoid writing struct node on the declaration of each struct object.
If he would just do:
struct node {
int data;
struct node *next;
};
you would have had to use:
struct node* node;
to declare a new node. And to avoid that you would have to define later:
typedef struct node Node;
in order to be able to declare objects like the following:
Node* node;
In the end:
typedef struct node {
int data;
struct node *next;
} Node;
Is just a shortcut for struct node { ... }; in addition to typedef struct node Node;.
Here struct node is a type like int
and Hence
struct node {
int data;
struct node *next;
}NodeVar;
means you are declaring a single variable Node of struct node.
like int intVar;
typedef is to make your code understandable.
so that when you use
typedef struct node Node;
you can use the same declaration as
Node NodeVar;
Consider this code:
#include <stdio.h>
typedef struct {
int data;
struct node *next;
} Node;
int main()
{
Node a, b = {10, NULL};
a.next = &b;
printf("%d\n", a.next->data);
}
This won't compile. The compiler has no idea what a struct node is, other than it exists. So you might change the definition in the struct to Node *next;. The typedef isn't in scope before it's declared, so it still won't compile. The simple answer is to do as he said, use the node tag after struct, and it works fine.
The lower case 'node' is a structure type... i.e. a struct node { stuff } is a node structure containing stuff.
On the other hand, the upper case "Node" is a completely new data type which refers to a 'struct node'
Generally (though in C++ I think you can), you cannot pass around a "node" in a C program... for example as an argument to a function. Rather, you would have to pass a 'struct node' as your argument...
// this will throw a syntax error because "node" is not a data type,
// it's a structure type.
void myFunc( node* arg );
// while this will not because we're telling the compiler we're
// passing a struct of node
void myFunc( struct node* arg );
// On the other hand, you *can* use the typedef shorthand to declare
// passing a pointer to a custom data type that has been defined
// as 'struct node'
void myFunc( Node* arg );

Resources