E
Enrico `Trippo' Porreca
Given:
typedef struct Node Node;
struct Node {
void *obj;
Node *next;
};
typedef struct Stack Stack;
struct Stack {
Node *top;
};
....is the following a conforming C function (I am particularly worried
about the casts), since I'm not modifying the obj parameter?
void *stack_push(Stack *s, const void *obj)
{
Node *n;
assert(s != NULL);
assert(obj != NULL);
n = malloc(sizeof *n);
if (n == NULL)
return NULL; /* push failed */
n->obj = (void *) obj;
n->next = s->top;
s->top = n;
return (void *) obj; /* successful push */
}
I can't make the obj field of struct Node a const void *, since the user
will probably free it by the "destructor" (I can't free a const void *,
right?):
void stack_destroy(Stack *s, void (*destroy)(void *))
{
Node *n, *tmp;
assert(s != NULL);
n = s->top;
while (n != NULL) {
tmp = n->next;
if (destroy != NULL)
destroy(n->obj); /* probably destroy == free */
free(n);
n = tmp;
}
free(s);
}
typedef struct Node Node;
struct Node {
void *obj;
Node *next;
};
typedef struct Stack Stack;
struct Stack {
Node *top;
};
....is the following a conforming C function (I am particularly worried
about the casts), since I'm not modifying the obj parameter?
void *stack_push(Stack *s, const void *obj)
{
Node *n;
assert(s != NULL);
assert(obj != NULL);
n = malloc(sizeof *n);
if (n == NULL)
return NULL; /* push failed */
n->obj = (void *) obj;
n->next = s->top;
s->top = n;
return (void *) obj; /* successful push */
}
I can't make the obj field of struct Node a const void *, since the user
will probably free it by the "destructor" (I can't free a const void *,
right?):
void stack_destroy(Stack *s, void (*destroy)(void *))
{
Node *n, *tmp;
assert(s != NULL);
n = s->top;
while (n != NULL) {
tmp = n->next;
if (destroy != NULL)
destroy(n->obj); /* probably destroy == free */
free(n);
n = tmp;
}
free(s);
}