I have created node
structure and created pointer of the same inside main
but didn't allocated memory for node structure
: struct node * first
or struct node * second
(which was supposed to be allocated dynamically- malloc
/calloc
). Instead, I am able to access data(or memory for structure)
#include<stdio.h>
struct node{
int data;
struct node *next;
};
void Traverse(struct node * head){
while (head!=NULL)
{
printf("Data:%d\n", head->data);
head=head->next;
}
}
int main()
{
struct node * first;
struct node * second;
first->data=33;
first->next=second;
second->data=45;
second->next=NULL;
Traverse(first);
return 0;
}
Currently I am running this code in VS Code so is this the VS Code which is doing it automatically or something else is happening internally?
If your definition of "work" is "apparently seems okay despite the fact it shouldn't be" then, yes, it works. However, I would contend that the correct definition of "works" should include the term "reliably" somewhere in it :-)
What you are doing there is undefined behaviour. This code specifically (inside a function, so using automatic variables):
struct node * first;
first->data = 33;
will assign an arbitrary value to first
which may or may not fail when assigning data to the memory it points to. But, whether it fails or not, it's still the wrong thing to do. Possible outcomes include (non-exhaustive):
Undefined behaviour is, well, ... undefined. That includes the subset of behaviour where it seems to work okay. But, if you rely on that, you will eventually suffer the consequences.