Checking if a pointer is allocated memory or not

前端 未结 18 1464
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 07:30

Can we check whether a pointer passed to a function is allocated with memory or not in C?

I have wriiten my own function in C which accepts a character pointer -

18条回答
  •  感动是毒
    2020-11-28 08:00

    There is a simple way to do this. Whenever you create a pointer, write a wrapper around it. For example, if your programmer uses your library to create a structure.

    struct struct_type struct_var;
    

    make sure he allocates memory using your function such as

    struct struct_type struct_var = init_struct_type()
    

    if this struct_var contains memory that is dynamically allocated, for ex,

    if the definition of struct_type was

    typedef struct struct_type {
     char *string;
    }struct_type;
    

    then in your init_struct_type() function, do this,

    init_struct_type()
    { 
     struct struct_type *temp = (struct struct_type*)malloc(sizeof(struct_type));
     temp->string = NULL;
     return temp;
    }
    

    This way,unless he allocates the temp->string to a value, it will remain NULL. You can check in the functions that use this structure, if the string is NULL or not.

    One more thing, if the programmer is so bad, that he fails to use your functions, but rather directly accesses unallocated the memory, he doesn't deserve to use your library. Just ensure that your documentation specifies everything.

提交回复
热议问题