void reserve(int x)
{
stream = begin;
if (begin == NULL)
{
begin = stream = (struct room*)malloc(sizeof(struct room));
details();
stream->following = NULL;
printf("\n\t room booking is successful!");
x = stream->room_period;
printf("\n\t your room period is: period-%d", x);
stream->room_period = x;
return;
}
After running details(), will the program automatically continue to run or some words need to be added ??
CodePudding user response:
If the function detals()
terminate (returns) then the following line in reserve()
will run which in this case is:
stream->following = NULL;
details
presumably sets the global variable stream. Otherwise it's undefined behavior as malloc()
does not initialize the memory being allocated. I suggest you avoid global variables if possible and instead pass them those variables as arguments:
details(&stream);
In C we don't cast void *
and I suggest you use the variable rather than the type as argument to sizeof
:
begin = stream = malloc(sizeof *begin);
You should check the return value from malloc()
. It will return
NULL on failure and this will cause the following stream->following
to segfault.
Not sure why you read a variable then write it back again to the same place. As x
is an argument whatever you assign to it will be discard when the function returns. At least in this sample x
isn't serving any purpose and could just be eliminated.
x = stream->room_period;
printf("\n\t your room period is: period-%d", x);
stream->room_period = x;
Maybe you just want to do this instead?
printf("\n\t your room period is: period-%d", stream->room_period);
Your function is missing a }
so this will not compile as is.
CodePudding user response:
A void
functions doesn't return a value to its caller, but it returns execution.
So the code following the call todetails()
will run once (and if) it returns.
If the function details()
calls exit()
or a similar function, then execution will not return and your process will terminate.
Aside:
- Casting the result of
malloc()
is redundant and may hide a bug. - Assuming
malloc()
can not fail is very optimistic and risks undefined behaviour. Check its return value.