Reputation: 49
So I was trying to use a global pointer that I define in a function and I'm going to use in another function without passing as parameters.
Here is my fun.c file
#include <stdio.h>
#include <stdlib.h>
int *step;
int step_counter;
int init(int num){
step = #
step_counter = *step;
return 0;
}
void reset_counter(){
step_counter = *step;
printf("%d ", step_counter);
}
Here is the main.c file
#include <stdio.h>
#include <stdlib.h>
#include "fun.c"
int main()
{
init(3);
reset_counter();
return 0;
}
I was expecting that the reset_counter function to print 3. But instead it prints out 0. I don't know what's the problem. I'm pretty new to C.
Upvotes: 0
Views: 60
Reputation: 310980
In this function
int init(int num){
step = #
step_counter = *step;
return 0;
}
parameter num
is a local variable of the function. After exiting the function the variable will not be alive and its memory can be reused by some other parts of the program.
As result the pointer step
will have an invalid value and the program will have undefined behavior if it'll try to access the memory pointed to by the pointer.
You could rewrite the function the following way.
int init(int num){
step = malloc( sizeof( *step );
int success step != NULL;
if ( success )
{
*step = num;
step_counter = *step;
}
return success;
}
You should not forget to free the pointer before exiting the program.
Though it is not clear why you need the additional variable step_counter
.
I would rewrite the code snippet the following way
int *step;
int init(int num){
step = malloc( sizeof( *step ) );
int success = step != NULL;
if ( success ) *step = num;
return success;
}
void reset_step(){
free( step );
step = NULL;
}
Upvotes: 1
Reputation: 36483
You have undefined behavior.
You point step
to the address of num
but num
is a local variable that's destroyed after init()
returns. Trying to derefence step
in reset_counter()
gives you UB as what it's pointing to is already destroyed.
Why are you using a pointer for step
? You could just use step = num;
and have step
be an int
.
Upvotes: 3