I have the following struct:
struct node {
int data;
struct node *next;
};
struct node *n1 = malloc(sizeof(struct node));
I am not sure how initialize all the pointer fields of struct pointer to NULL without causing any potential for memory leaks?
You need to initialize the members of the structure after you allocate it with malloc:
struct node {
int data;
struct node *next;
};
struct node *n1 = malloc(sizeof(struct node));
n1->data = 0;
n1->next = NULL;
If you want to initialize your structure in one step with default values, which can be handy if it is much larger, use a static structure with these defaut values:
struct node def_node = { 0, NULL };
struct node *n1 = malloc(sizeof(struct node));
*n1 = def_node;
Alternately, you can use the C99 syntax:
struct node *n1 = malloc(sizeof(struct node));
*n1 = (struct node){ 0, NULL };
As commented by Leushenko, you can shorten the initializer to { 0 } for any structure to initialize all members to the appropriate zero for their type:
struct node *n1 = malloc(sizeof(struct node));
*n1 = (struct node){ 0 };
You have four choices:
1) Set the pointers manually, e.g. node-> next = NULL;
2) Use calloc() to zero out the memory when you allocate it
3) Use memset() to zero out the memory after you've allocated it.
... OR ...
4) Don't worry about explicit initialization until you actually need to use the struct. Design your program such that you make sure any pointer is assigned before you try to read it.
FYI, this is one of the main purposes of a "constructor" in OO languages like C++ or C#: to initialize "class invariants".
PS:
5) I forgot about C99 struct initialization, which Leushenko mentioned:
what is the difference between struct {0} and memset 0
struct A
{
int x;
int y;
};
...
A a = {0};
This is vastly preferred to either calloc() or memset().
It also applies to other initialization values besides "0":
C99 Standard 6.7.8.21
If there are fewer initializers in a brace-enclosed list than there
are elements or members of an aggregate, or fewer characters in a
string literal used to initialize an array of known size than there
are elements in the array, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage
duration.
Related
// Linked list implementation in C
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
int value;
struct node *next; //What is this, what are we doing here?
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}
int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
// Assign value values
one->value = 1;
two->value = 2;
three->value = 3;
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;
// printing node-value
head = one;
printLinkedlist(head);
}
I want to ask what are we doing here with this line of code?
it's in the creating a node part of the code (top).
struct node *next;
Are we assigning a pointer type struct variable for the sturct node but its inside of the same struct, assigning a variable named *next inside the same struct? But that isn't allowed, right?
we can either declare the variable out side the } and between ; or in the main()
function part of the code only, Isn't it?
Like
main()
{
struct node *next;
}
Again, then I came across a post mentioning it as a pointer to the structure itself, can anyone explaine how can we do this inside the same struct?
The next member points to another instance of struct node. Graphically, we usually represent it like this:
+–––––––+––––––+ +–––––––+––––––+
| value | next |––––> | value | next |
+–––––––+––––––+ +–––––––+––––––+
A struct type cannot contain an instance of itself - we can’t create a type like
struct node {
int value;
struct node next;
};
for two reasons:
The type definition isn’t complete until the closing }, and you cannot create an instance of an incomplete type;
The type would require infinite storage (struct node contains a member next of type struct node which contains a member next of type struct node which contains a member next of type struct node...);
However, we can declare next as a pointer to struct node, since we can create pointers to incomplete types. The size and representation of a pointer is independent of the size and representation of the type it points to.
What it means
The line struct node *next; is read as "next is a pointer to another struct node".
This is just a recursive structure declaration (definition):
struct node {
int value;
struct node *next; //What is this, what are we doing here?
};
It says a node consist of two parts:
an integer value
a pointer to another node.
The wiki article on linked lists has a nice visualization showing how one node points to another (or to NULL to end the chain).
How does it work?
As you noted, the interesting part is how the declaration can include a reference back to itself. The compiler handles this in two steps:
It sizes the struct as consisting of an int and a pointer (they're all the same size regardless of what they are pointing to).
Later it type checks the assignment and generates the appropriate assembly. When you write one->value = 1;, it makes sure the 1 is an integer and generates code to move 1 to the integer slot. And when your write one->next = two;, it verified that two is a pointer to a node and generates code to move that pointer to the second slot for the struct node pointer.
All the implementations I have seen online use pointer to declare nodes and then will use malloc to create space for them like this:
struct Node
{
int data;
struct Node *next;
};
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
...
But I can also create the same without pointers and malloc like this:
struct node {
int id;
struct node* next;
};
struct node head = {0, NULL};
struct node one = {1, NULL};
struct node two = {2, NULL};
struct node tail = {3, NULL};
int main(){
head.next = &one;
one.next = &two;
two.next = &tail;
...
My question is, why the 1st method is mostly the one used, why do we need to declare each node as pointer and why do we need malloc?
(Just to point out I know why struct Node *next; is declared as pointer int the struct declaration).
You should do this with local variables, not global ones, but the general idea would be the same. You should also steer towards having arrays and not heaps of otherwise unrelated variables:
struct node {
int id;
struct node* next;
};
int main(){
struct node nodes[4];
for (int i = 0; i < 4; ++i) {
nodes[i].id = (3 - i);
if (i != 0) {
nodes[i].next = &nodes[i-1];
}
}
return 0;
}
Where something like that assembles them in reverse order for convenience, but they're all grouped together in terms of memory initially.
malloc is used because you often don't know how many you're going to have, or they get added and removed unpredictably. A general-purpose solution would allocate them as necessary. A specialized implementation might allocate them as a single block, but that's highly situational.
Here the lifespan of nodes is within that function alone, so as soon as that function ends the data goes away. In other words:
struct node* allocateNodes() {
struct node nodes[10];
return &nodes; // Returns a pointer to an out-of-scope variable, undefined behaviour
}
That won't work. You need a longer lived allocation which is precisely what malloc provides:
struct node* allocateNodes() {
struct node *nodes = calloc(10, sizeof(struct node));
return nodes; // Returns a pointer to an allocated structure, which is fine
}
The problem is if you malloc you are responsible for calling free to release the memory, so it becomes more work.
You'll see both styles used in code depending on the required lifespan of the variables in question.
If you know ahead of time exactly how many items will be in your list, then you're probably better off using an array rather than a list. The whole point of a linked list is to be able to grow to an unknown size at runtime, and that requires dynamic memory allocation (i.e., malloc).
Im trying to create a linked list in C, where each node has a specific size entered by the user when the program launches. I already thought of a struct:
struct ListNode{
char * str;
struct ListNode * next_node;
};
but here the size of each node is fixed. Any ideas?
Thanks a lot in advance.
It seems you need your data size that the node holds to change each time. You can achieve this by using a constant size node that holds a pointer to dynamically allocated data.
Note that in the example below the struct size stays sizeof(void*)+ sizeof(node*)
but the size of data allocated for each node changes using the user input.
typedef struct Dnode
{
void* data;
struct Dnode* next;
}Dnode;
Dnode* CreateDnode(size_t data_size_bytes)
{
Dnode* newNode = NULL;
newNode = malloc(sizeof(Dnode));/*always the same*/
if(NULL == newNode)
{
return NULL;
}
newNode->data = malloc(data_size_bytes);/*changes by input*/
if(NULL == newNode->data)
{
return NULL;
}
newNode->next = NULL;
return newNode;
}
Sounds like you may be looking for the "flexible array member" feature whereby an incomplete array is placed at the end of a structure:
struct ListNode {
struct ListNode *next;
char data[];
};
This is allocated like:
struct ListNode *node = malloc(sizeof *node + data_size_bytes);
Then we can store values in node->data[i] for i from 0 to data_size_bytes - 1. The whole structure and data are in one linear block.
Note that a structure with a flexible member can't be used as an array element type.
Before the ISO C standard added the flexible array member in 1999, this was done as a popular "struct hack" using an array of size 1. If you're constrained to working in C90 it goes like this:
struct ListNode {
struct ListNode *next;
char data[1];
};
Now sizeof ListNode includes the one element array, and quite likely padding for alignment. For instance on a system with four byte pointers, the size is quite likely eight. If we use the same malloc line, we will allocate excess memory. The right malloc expression to use for the C90 struct hack:
#include <stddef.h>
struct ListNode *node = malloc(offsetof(struct ListNode, data) + data_size_bytes);
Unlike the flexible array member feature, the struct hack doesn't have formally well-defined behavior; it's just something that "works if it works".
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).
I have a simple question in understanding the pointers and struct definitions in the linked list code.
1)
typedef struct node
{
struct node* next;
int val;
}node;
here if I use two "node" when i initialize node *head; which node I am referring to?
2) Here I use an int val in the struct. If I use a void* instead of int is there any thing thats going to change ?
3)Also if I pass to a function
reverse(node* head)
{
node* temp = head; or node* temp = *head;
//what is the difference between the two
}
I am sorry if these are silly question I am new to c language.
Thanks & Regards,
Brett
<1>
in C you need to specify struct node for structs
struct node
{
...
} node;
the last 'node' is variable of type struct node
e.g.
node.val = 1;
and not a type.
if you want to use 'node' as a type you need to write
typedef struct node { .. } node;
<2>
if you use void* you will need a mechanism to handle what the pointers point to e.g. if void* points to an integer you need keep the integer either on the stack or the heap.
node n;
int value = 1;
n.val = &value; // pointing to a single integer on stack
int values[]={1,2,3};
n.val = values; // pointing to an array of integers on stack
void* ptr = malloc(sizeof(int));
n.val = ptr; // pointing to a single (uninit) integer allocated on heap
int* ptrval = (int*)ptr; // setting an int ptr to the same memory loc.
*ptrval = value; // ptrval now points to same as n.val does
<3>
reverse(node* head)
head is a pointer to your list, *head is the content of what the pointer points to (first node below)
head->[node next]->[node next]->[node
next]
EDIT: rephrased and edited.
EDITx2: apparently the question got edited and a typedef was added so the question was altered.
*head is the dereference of the pointer : ie the actual place in memory that is pointed to by the pointer head...
Think of head as a coat hanger and *head as the coat itself, if that helps.
ie:
struct * coat c; //this is a coat hanger, not a coat
....
struct coat k = *c;//this is the coat itself, not a coat hanger
For #1:
In C, struct's have a separate name space. So if you wrote:
struct foo { ... };
You then have to use struct foo to reference the type. If you tried just foo after the above definition, the compiler would give an error as it doesn't know anything about that unqualified name.
A typedef gives a type an alternate name. A typedef name does not need to be qualified, so once you do:
typedef struct foo foo;
You can now use an unqualified foo to reference the type. Since it's just an alternate name, you can now use struct foo and foo interchangeably.
For #2.
It's possible that if you changed val to a void * it could change the size of the entire structure. Whether that makes a difference will depend on how you've written the rest of your code.