Thread: Question about dynamic memory allocation

1. Question about dynamic memory allocation

Hi guys , i have a question about din. memory alloc. and i want to ask it with an example.

Code:
```/* here is my struct */
struct node
{
int data;
struct node *next;
}
/* here is my simple making node function*/

struct node *makenode(int value)
{
struct node *np;
np=malloc(sizeof(struct node));
np->data=value;
np->next=NULL;
}```
What if i did not write the np=malloc(sizeof(struct node)); line, Does the code work properly ? When i need to take a place from memory using with pointer and when i dont need ? Thank you for your answers.

2. Originally Posted by dayanike
Code:
```        struct node *np;
np=malloc(sizeof(struct node));
np->data=value;
np->next=NULL;
}```
What if i did not write the np=malloc(sizeof(struct node)); line, Does the code work properly ?
No - in this case, np would be uninitialized and could point anywhere, so np->data could be located anywhere in your address space. So you don't know what you might be trying to modify.

3. Originally Posted by dayanike
When i need to take a place from memory using with pointer and when i dont need ?
Basically if you want to use the contents of what that pointer points to you will always need to have allocated space.

If you want to iterate through a linked list, you could do:

Code:
```int find (struct node * root, int value){
struct node * t; /* you don't need to allocate memory here */

t = root; /* t will point to an already allocated space in memory */

while (t != NULL) {
if (t->data == value)
return 1;

t = t->next;
}

return 0;
}```
Pointers are variables which store memory addresses. When you declare them they are storing a random address whose contents are not known. So you initialize them by allocating space or making them point to an already allocated space.

You can also assign them to NULL which is an initialization, but in this case the pointer is still pointing to something now known.

Edit: There's this small tutorial which covers very nice features of pointers, give it a look.

Popular pages Recent additions