Reputation: 433
The result of code 1 is still 10
after you free pointer p
and p
is not NULL
.
the inputs of code 2 are 5
(length) and 1 2 3 4 5
for the value of each node, but the output is nothing under the condition that all the following nodes are not NULL
.
My question is that based on the logic of code 1, shouldn't all the values of nodes be printed because they are not NULL
?
Can anyone explain to me? Thank you so much!
code 1:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = (int*)malloc(sizeof(int));
*p = 10;
free(p);
if (p != NULL) {
printf("%d\n", *p);
}
return 0;
}
code 2:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
struct Node *next;
int value;
} Node, *list;
list create_Node() {
list head = (list)malloc(sizeof(Node));
if (!head)
exit(-1);
list tail = head;
int len;
int val;
printf("Please enter the length of the list:\n ");
scanf("%d", &len);
for (int i = 0; i < len; i++) {
list new = (list)malloc(sizeof(Node));
if (!new)
exit(-1);
printf("Please enter the value of the node:\n ");
scanf(" %d", &val);
new->value = val;
tail->next = new;
tail = new;
}
return head;
}
int delete_List(list l) {
if (l == NULL) {
printf("List is empty!");
exit(-1);
}
list temp;
while (l) {
temp = l->next;
free(l);
l = temp;
}
return 1;
}
int main() {
Node *n = create_Node();
n = n->next;
delete_List(n);
while (n->next != NULL) {
printf("%d\n", n->value);
n = n->next;
}
return 0;
}
Upvotes: 0
Views: 108
Reputation: 32594
having
int main(){ int *p = (int*)malloc(sizeof(int)); *p = 10; free(p); if(p!=NULL) { printf("%d\n",*p); } return 0; }
My question is that based on the logic of code 1, shouldn't all the values of nodes be printed because they are not NULL??
Except in the case there are no more memory the malloc will works and return a non null value, after the free the value of p is unchanged and still non null so the code try to read in the free memory and this is an undefined behavior
There are better way to ( try to) print a random value :-)
in code 2 this is the same, you access to free memory, both in the test of the while and in the printf and the value to assign n
Upvotes: 0
Reputation: 172478
...based on the logic of code 1...
Code 1 accesses freed memory (a so-called dangling pointer), which is undefined behavior. Anything can happen, including, but not limited to, your program crashing, the last value being returned (= the behavior you observed) or the program doing something completely unexpected.
Thus, you cannot infer anything from "the logic of code 1".
Upvotes: 2