struct node *link = (struct node*) malloc(sizeof(struct node));
The above code is part of a larger program that creates a linked list. I already have and understand the code that leads up to this which creates the structure "node". I just am unsure what the code I provided does in regards to that structure.
The above code simply allocates memory of dimension "struct node", then cast it to the same type and assign the returned pointer to a variable called link.
Well, let's go through it piece by piece....
First, this tells that you are after a pointer to a struct of type node not a struct node but a pointer that points to a memory location holding a struct node
struct node *link = ...
then, let's have a look at the signature of the malloc() function.
void *malloc(size_t size);
It tells us that the return type is void *, which , in C, can be casted to any other type and generally used to provide a universal interface to the caller (similar to but not same as templates in C++ or other languages).
With the below cast, we are casting void *, the return type of malloc() to a pointer to a struct of type node, i.e. struct node*
(struct node*) malloc(...);
Looking at the argument passed to the malloc() function, which gives the size of an expression measured in char-sized storage units (sizeof(char) is guaranteed to be 1)
...sizeof(struct node)...
you are asking your compiler to return you the size of your struct node (this, of course, depends on the members of your struct).
Putting it all together...
struct node *link = (struct node*) malloc(sizeof(struct node));
allocate memory as big as a struct of type node can fit and return me a pointer to the start of this memory chunk. At the same time, mark this chunk of memory so that you (the compiler) will know that this area is reserved for a struct of type node
Edit : In C, you do not need to cast the type of the pointer returned by malloc() to another pointer type. In your case, the returned void * pointer from malloc() is automatically promoted to the appropriate pointer type, i.e. struct node*.
Related
Im new to community this is my first post so hello to everyone.
I have recently started studying the coding and c language in specific.But i have a confusion when it comes to structures and how they are referenced in memory.
This is example when my lack of understanding makes me unable to understand what exactly happening in code.
For example when asking malloc for space for lets say a node structure the way i understood it until now is that computer will allocate memory of size of struct if instructed by size of operator in parenthesis. Therefore that many memory locations will be allocated starting at specific location pointer points to.But when we use pointer of struct type we allocated memory for (in this case struct node) it just stores a address of first byte of said struct as all pointers do if i understand correctly.
Then when
`*(pointername).exactfieldname
For example if we assume there is node structure defined in code.With two fields for int called numbers and for pointer called next.
node *n=malloc (sizeof(node));
*(n).next=malloc (sizeof(node));
syntax is used i cant understand how it works exactly.How is a computer just through pointer to a first byte out of certain number of bytes that were allocated suddenly able to access fields of structure?
Reason this is additionally confusing is because when defining a node struct for linked list for example it is possible to define pointer to struct of struct type being defined before it is defined because its just a pointer so it only stores address. Due to that fact struct pointer cant have any special property allowing it to access fields its still just a pointer right?
When pointer is derefrenced does it mean that computer goes to pointed location and enters a strucutres. And then rest of syntax after dereferencing pointer like *(pointer ).fieldname can be used because now computer is inside structure and interacts with it and .fieldname refers to that instruction now?
I'll try to answer despite your question lacking some clarity.
If I get you right, you are confused by this:
typedef struct node {
struct node *next; // <<<< here
some_type_t data;
} node;
In the line marked, the compiler does not yet know what struct node looks like.
That is correct. It doesn't need to know that because we only store a pointer.
In that place you cannot define a non-pointer element of that type (or any other incomplete type) for exactly that reason.
Now if you come to that part:
node *n=malloc (sizeof(node));
n->next=malloc (sizeof(node));
(Note: Your syntax was incorrect)
You seem to wonder how the compiler would know what n->next really is as it was unknown when the struct was defined.
That does not matter.
It is known when the compiler comes to this line. You can only dereference a pointer if the type is fully known in that location.
The compiler now knows what node* means and can address the fields in *n and in the same way it can deal with n->next.
Study and try do understand the following code.
Compare the values that are printed out. %p will print address values (hex format) and %d prints decimal values.
Take a good look at the parameters that are passed to the printf function. & is the 'address of' operator and -> is a dereference operator, which is equal to *(pointer)..
struct node {
struct node *next; //pointer to struct node
struct data_rec { //embedded struct
int value; //some value of type int
} data; //data of type struct data_rec
};
//allocation on the heap -> pointer to struct node
struct node *allocated_node = malloc(sizeof(struct node));
allocated_node->next = NULL;
allocated_node->data.value = 0;
//allocation on the stack (sizeof(struct node) bytes)
struct node base_node;
base_node.next = allocated_node;
base_node.data.value = 42;
//prints some information of the node
void printNodeInfo(struct node *node_)
{
printf(
"address of node: %p\n"
"address of node.next: %p\n"
"value of node.next: %p\n"
"address of node.data: %p\n"
"address of node.data.value: %p\n"
"value of node.data.value: %d\n",
node_,
&node_->next,
node_->next,
&node_->data,
&node_->data.value,
node_->data.value
);
}
int main()
{
printNodeInfo(&base_node);
printNodeInfo(allocated_node);
return 0;
}
I'm a C beginner, and I came across this code while trying to implement a linked list.
struct Node *ptr = malloc(sizeof(*ptr));
The Node struct looks like this:
struct Node {
int data;
struct Node *next;
};
I'm trying to understand the first line. It seems as if malloc(sizeof(*ptr)) already knows the contents of ptr. What exactly is happening on the left side and is it happening before malloc is called?
It seems as if malloc(sizeof(*ptr)) already knows the contents of ptr.
Actually, it doesn't. The sizeof operator doesn't actually evaluate its operand (unless it's a variable length array), it just looks at its type. This means that ptr isn't actually dereferenced and is therefore a safe operation.
Only use paranthesis with sizeof if there's a type you'd like to know the size of. If you have an expression, like *ptr, it's enough to write:
struct Node *ptr = malloc(sizeof *ptr); // <- no parenthesis
The expression *ptr dereferences the pointer so it becomes a struct Node and that's what the sizeof is returning the size for.
sizeofexpression - Returns the size, in bytes, of the object representation of the type of expression. No implicit conversions are applied to expression.
It's the same size you get if you do:
struct Node *ptr = malloc(sizeof(struct Node)); // <- parenthesis needed
but the first alternative is often preferable for clarity.
You need to allocate a memory for an object of the type struct Node declared like
struct Node {
int data;
struct Node *next;
};
So in the call of malloc you need to specify the size of the memory to be allocated for an object of this type. The function malloc returns a pointer to the allocated memory.
So you can write
struct Node *ptr = malloc( sizeof( struct Node ) );
On the other hand, the expression *ptr has the type struct Node. That is the declared pointer ptr has the pointer type struct Node * and dereferencing such a pointer like *ptr yields an expression of the type struct Node.
So you may rewrite the above record also like
struct Node *ptr = malloc(sizeof(*ptr));
because in this case sizeof( struct Node ) is equivalent to sizeof( *ptr ).
That is the compiler needs to know the type of the operand of the operator sizeof that to determine the size of an object of that type.
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
//and
struct node *tempNode = malloc(sizeof(struct node));
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
you're dynamically allocating space to a node pointer tempNode and typecasting it to be a struct node* type. (pointer to structure)
struct node *tempNode = malloc(sizeof(struct node));
The same as above, except without the explicit typecast (struct node*)
There is no difference. Since malloc returns type void *, it can be assigned to a variable of any pointer type without casting. As John Bode mentioned, casting the result of malloc is considered bad practice because it may mask the compiler error that would result from having some other definition of malloc.
Since you are casting it correctly there's no difference between the two.
But the cast is generally frowned upon in C since a void* can be implicitly converted into any other (data) pointer type.
Also see this C FAQ entry: What's wrong with casting malloc's return value?
A third one is there:
struct node *tempNode = malloc(sizeof *tempNode);
which is better since it makes for less changes in case the type is changed.
With the call to malloc, memory is allocated that has the size of the struct node in bytes. It returns a void* to the allocated memory.
Now the thing is: both of your lines do exactly the same, but the second line will lead to a warning when compiled with a C++ compiler.
C allows implicit conversion of a void* to a different pointer type, whereas the C++ compiler will - at least - warn you, or give you an error.
In the books I read that the syntax for malloc is malloc(sizeof(int)) but in one of doubly linked list program I see the following:
newnode=(struct node *)malloc(sizeof(struct node))
What is (struct node*) doing here? What is this entire code doing? btw, the code for the struct in the program is as below.
struct node
{
char line[80];
struct node *next,*prev;
};
struct node *start=NULL,*temp,*temp1,*temp2,*newnode;
Thank you
The code is dynamically creating a pointer to a single type of struct node. In most versions of C, the (struct node *) cast is not needed, and some argue that it shouldn't be used. If you remove the cast, it will be a void*, which can be used for any type.
Therefore:
newnode = (struct node*)malloc(sizeof(struct node));
is roughly equivalent to:
newnode = malloc(sizeof(struct node));
See: Specifically, what's dangerous about casting the result of malloc?
Note 1: If you are using Visual Studio to write your C code, it will give you red underlining if you don't cast the result of malloc. However, the code will still compile.
Note 2: Using malloc in C++ code requires you to cast the result as shown in your example.
You ran into a very bad code. C programmers never cast a result of malloc(). Not only it is not needed but can be harmful.
You should pass the number of bytes that you want malloc to allocate as argument. That is why in this code sample you use sizeof(struct node) telling C to allocate the number of bytes needed for a struct node variable. Casting the result like is shown in this code is bad idea by the way.
malloc returns a void pointer .
(struct node*) does a explicit conversion from void pointer to the target pointer type
"malloc" returns a void-pointer. (struct node *) is type-casting the result of malloc to a "node struct pointer", which is (undoubtibly) what "newnode" is.
struct node
{
int info;
struct node *link;
}*start;
void main()
{
struct node*tmp,*q;
tmp=(struct node*)malloc sizeof(struct node);
}
now my first question is when we declare structure is any struct type node is created in memory?
second question is ,if yes then here i take a start pointer which is pointing to struct type node so without specifying the address of struct node to start pointer how start pointer pointing the struct type node which is created during declaration plz clear me this how internally this is happening i have lot of confusion on that
third question is initially tmp and q pointer variable all are pointing towards the same struct node
plz expalin the concept malloc and calloc how internally they create node
thx for helping me out
You can declare a structure type without declaring any variables. However, your code defines a pointer variable, start.
The variable start is initialized to 0, so it is not pointing to anything.
The variables tmp and q are not initialized at all and cannot be safely used until assigned a value. You initialize tmp in the next line; q is still uninitialized.
malloc() provides space for the pointer to point to; it does not initialize that space. The value in tmp->info is indeterminate; the value in tmp->link is indeterminate too. If you had used calloc(), then tmp->info would be zero and tmp->link would be null (on all practical systems — theoretically, there could be a system where tmp->link was not properly initialized).
Finally, note that void main() is bad. The C standard says that the return type of main() should be int. Further, unless you've got a C99 or later compiler, you should include return(0); or equivalent as the last line in main() — or a call to exit().