Re: Why this code is working
- From: Simon Biber <news@xxxxxxxxx>
- Date: Tue, 01 Nov 2005 02:20:55 +1100
jammie_linux@xxxxxxxxx wrote:
Simon wrote : "String literals always have static duration, no matter where you declare them."
Is the same is also true when you allocate memory via malloc and other related function
Similar. The memory block allocated by the 'malloc', 'calloc' or 'realloc' functions will remain valid until the base address of the block is passed to the 'free' function. It doesn't matter whether the pointer gets passed to or from functions.
> like in the case below:
Also, in this code the getnode() is not returning anything explicitly( even though it should), still it is implicitly returning the value of node * q defined locally in it.
It's not implicitly returning anything. The code is wrong, and will not compile.
Is this what the standard says or is happening at the mercy of the compiler?
After you fix the errors below, the code is valid according to the standard. It should compile and run on all C compilers.
#include <stdio.h> #include <stdlib.h>
typedef struct node { int data; struct node * next; }node;
node * getnode() { node * q = malloc(sizeof(node)); if(q == NULL) { printf("Insufficient memory\n"); exit(1);
The exit code 1 is not defined by the C standard, and could have unintended effects. If you want to indicate that the program failed, you should write
exit(EXIT_FAILURE);
}
q->data = 9; q->next = NULL;
You should have the line return q; here.
}
void display(node *q) { if(q == NULL) { printf("q is NULL in display\n"); exit(1); } printf("%d %p\n",q->data, (void*)q->next); return; }
int main(void)
{
node * q;
q = getnode();
display(q);
You should have the line free(q); here.
return 0 ; }
Once you correct the errors shown above, this code is fine.
-- Simon. .
- References:
- Re: Why this code is working
- From: Simon Biber
- Re: Why this code is working
- Prev by Date: Re: need of a sprintf like function...
- Next by Date: Re: what is the meaning of exit()?
- Previous by thread: Re: Why this code is working
- Next by thread: Re: Why this code is working
- Index(es):
Relevant Pages
|