My doubt is simple, when I allocated memory using malloc in my c program. Mistakenly I used this syntax
struct node {
int data;
int sat;
int gau;
struct node* next;
};
int main() {
struct node *head;
struct node *newnode;
newnode = (struct node*)malloc(sizeof(struct node *);
if(newnode != NULL) {
newnode -> data = 5;
newnode -> sat = 10;
newnode -> gau = 15;
newnode -> next = head;
head = newnode;
}
}
In line newnode = (struct node*)malloc(sizeof(struct node *);
I accidently put sizeof(struct node *));`
this will allocate the memory equivalent to the sizeof(pointer) = 4 or 8 bytes.
But the code does not seg fault.
Why is this happening?
To understand this I tried another program with a slight change. I took a large int array inside the struct node and also this time I passed 0 to malloc.
struct node {
int data;
int sat;
int gau;
long long int a[1000];
struct node* next;
};
int main() {
struct node *head;
struct node *newnode;
newnode = (struct node*)malloc(0);
if(newnode != NULL) {
newnode -> data = 5;
newnode -> sat = 10;
newnode -> gau = 15;
newnode -> next = head;
newnode -> a[999] = 10;
head = newnode;
}
}
For me, this code also works. But, there should be some invalid memory access check which should make this code seg-fault or something? In this case seg-fault is not occuring, means there is definitely some memory which is getting accessed which should not be accessed by this program as it has not reserved it for itself using malloc. Why there is no error while executing this program?