jackjop jackjop - 1 month ago 8
C Question

Calling a method in if statement breaks down variables

I have a code like this

int i;
for(i=0; i<n ; i++)
{
....

char* ref_error = "";
if( isSeatAvailable(&tmp, movie_name, seat_number, &ref_error) == 0)
{
printf("available %s\n", seat_number);
}
else
{
logError(ref_error);
}

....
}


If
isSeatAvailable
returns
0
, it works perfectly, but it returns
-1
and the program continues to else statement, the variables breaks down: like n becomes 4509408 etc.

The thing is,
If I re-write code like this and call
isSeatAvailable
method outside of if statement, it works perfect!

int i;
for(i=0; i<n ; i++)
{
....

int res = isSeatAvailable(&tmp, movie_name, seat_number, &ref_error);
if( res == 0)
{
printf("available %s\n", seat_number);
}
else
{
logError(ref_error);
}

....
}


What might cause the problem here?

Here's the method I'm calling

int isSeatAvailable(hall** halls,char* movie_name,char* seat_no, int ticket_count, char** ref_error)
{

....
sprintf(*ref_error,"Seat %s is not defined at %s.",seat_no,tmp->hall_name);
....
}

Answer

The problem is in the call to sprintf. The first parameter ref_error comes from:

char* ref_error = "";

And now sprintf tries to overwrite the constant "" with the error message. Strange things will follow!

sprintf needs a real buffer (of sufficient size) to store the message into. Not just a pointer.