I wonder that is it possible to check if a variable is still in scope in c or if a pointer points to a variable that is out of scope. What I ultimately want to do is check the pointers that and if they point to a variable that is out of scope then drop the pointer by calling free. so if you guys could help me I would be more than happy. thank you all for you contrubutions.
>Solution :
EDIT:
You could also skip the structure part and just set the pointer to NULL with macros and then check if it’s NULL with a macro;
void some_function(int* input)
{
if (CHECK_POINTER(input))
{
*input = 50;
}
};
int main()
{
int* point ;
CLEAR_POINTER(point);
int a=-1;
some_function(point);
printf("%d\n", a);
ASSIGN_POINTER(point, &a);
some_function(point);
printf("%d\n", a);
}
OLD:
If you are trying to keep track if the pointer is assigned to a certain variable, you could use a structure that contains the pointer variable itself and a variable that is either 0 or 1 when the pointer has been assigned to certain variable.
You can then use macros to assign pointer, clear pointer or check if pointer is assigned a variable address;
#include <stdio.h>
#define DEFINE_POINTER_DATA_STRUCTURE(data_type)\
typedef struct \
{ \
int is_assigned; \
data_type *pointer; \
}PDS_##data_type;
#define POINTER_DATA_STRUCTURE(data_type) PDS_##data_type
// The above allows you to have custom types
DEFINE_POINTER_DATA_STRUCTURE(int) // Define a struct of int pointer
#define ASSIGN_POINTER(structure, address) structure.pointer = address; structure.is_assigned = 1;
#define CLEAR_POINTER(structure) structure.pointer = 0x00; structure.is_assigned = 0;
#define CHECK_POINTER(structure) structure.is_assigned
#define GET_POINTER(structure) structure.pointer
void some_function(POINTER_DATA_STRUCTURE(int) input)
{
if (CHECK_POINTER(input))
{
*GET_POINTER(input) = 50;
}
};
int main()
{
POINTER_DATA_STRUCTURE(int) pointer_structure;
CLEAR_POINTER(pointer_structure);
int a=-1;
some_function(pointer_structure);
printf("%d\n", a);
ASSIGN_POINTER(pointer_structure, &a);
some_function(pointer_structure);
printf("%d\n", a);
}