Janice said:
Always get segmentation fault for the following code.
If the data is primitive type instead, it will be fine.
What is the problem?
Thanx
#include said:
main() has return type int; make this
int main (void) {
typedef int pid_t;
pid_t pid=12;
pid_t* ary;
int count=0;
ary=(pid_t*)realloc(ary,(count+1)*sizeof(pid_t));
realloc() works on memory previously allocated by malloc().
As ary is initialized with an arbitrary value, realloc() tries
to access the information somewhere. You are lucky that it
crashes and not seems to work.
Also, it is a Bad Idea (TM) to cast the return value of
malloc and realloc. Don't do this. Just use google groups
search on comp.lang.c to find out why.
Note: If you use sizeof *ary instead of sizeof(pid_t),
this works even if you change the type of ary.
Your code does not work if you throw out the typedef
and replace pid_t by int, so there is no surprise.
Note: Do not use typedef at block scope. Sooner or later,
you will go for functions and will need a typedef at
file scope. Even better: Put it into a header file, then
you can #include it in order to make it available.
The comp.lang.c FAQ will help you understand the issues.
Best download the ASCII version and search through it for
malloc(), realloc(), typedef, ... Start here:
http://www.eskimo.com/~scs/C-faq/top.html
Cheers
Michael