Malloc() & Free()


struct node{

char *data;
struct node *link;
};

struct node first;

int main()
{
char *ptr;
ptr=malloc(sizeof(char)*100);
first=malloc(sizeof(struct node));
first->data=ptr;
first->link='\0';
free(first);
free(ptr);
return 0;
}


Experts, Please say what is the wrong with this code ? Am I try to free the memory address which is already free?

Please give me the explanation. If it is possible provide me the pictorial explanation.

Thank you.
You're treating 'first' like it's a pointer, but it's not a pointer.

1
2
//struct node first;   <---  not a pointer
struct node *first;  // <--- a pointer 


Other than that, I don't see anything wrong. first->link='\0'; is a little weird, but shouldn't be a problem.
Thank you for replay. Sorry for the typing mistake... Original code like below

struct node{

char *data;
struct node *link;
};

struct node *first;

int main()
{
char *ptr;
ptr=malloc(sizeof(char)*100);
first=malloc(sizeof(struct node));
first->data=ptr;
first->link='\0';
free(first);
free(ptr);
return 0;
}

[This code are making run time problem in my linux os. Trying to free the unallocated memory]
Works for me.
Topic archived. No new replies allowed.