structure defintion vs declaration question

C

Chad

Given the following.....

#include <stdlib.h>
#include <stdio.h>

struct node {
int data;
struct node *next;
};

int main(void)
{
struct node* head;

head = malloc(sizeof(struct node));
head->data = 1;
head->next = NULL;

head = head->next;

free(head);

return 0;
}


Is struct node *next defintion or declaration?
 
V

vippstar

Given the following.....

#include <stdlib.h>
#include <stdio.h>

struct node {
int data;
struct node *next;

};

int main(void)
{
struct node* head;

head = malloc(sizeof(struct node));
head->data = 1;
head->next = NULL;

head = head->next;

free(head);

return 0;

}

Is struct node *next defintion or declaration?

It's a declaration.
See 6.7.2.1
 
A

Anand Hariharan

Given the following.....

#include <stdlib.h>
#include <stdio.h>

struct node {
int data;
struct node *next;
};

int main(void)
{
struct node* head;

head = malloc(sizeof(struct node));
head->data = 1;
head->next = NULL;

head = head->next;

free(head);

return 0;
}


Is struct node *next defintion or declaration?

After noting vippstar's response to your immediate question ...
.... hope you are aware that your code is leaking memory.

Also, I'd suggest you review the currently active thread 'Pointer
dereference rather than sizeof' and see if you might reconsider how you
wrote your malloc statement.

- Anand
 
C

Chad

After noting vippstar's response to your immediate question ...
... hope you are aware that your code is leaking memory.

Also, I'd suggest you review the currently active thread 'Pointer
dereference rather than sizeof' and see if you might reconsider how you
wrote your malloc statement.

Okay, how is the code leaking memory? I should see it, but for some
reason, I don't.
 
V

vippstar

Okay, how is the code leaking memory? I should see it, but for some
reason, I don't.


I did not review your code, just answered your question.
However, your code practically does this:

p = malloc();
/* ... */
p = NULL;
free(p);

(note: free(NULL) is defined to do nothing)

Not only you leak memory, but you fail to check the return value of
malloc, so you are also possibly dereferencing a null pointer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top