Checking if a pointer is allocated memory or not

前端 未结 18 1208
伪装坚强ぢ
伪装坚强ぢ 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 07:41

    Well, I don't know if somebody didn't put it here already or if it will be a possibility in your programme. I was struggling with similar thing in my university project.

    I solved it quite simply - In initialization part of main() , after I declared LIST *ptr, I just put that ptr=NULL. Like this -

    int main(int argc, char **argv) {
    
    LIST *ptr;
    ptr=NULL;
    

    So when allocation fails or your pointer isn't allocated at all, it will be NULL. SO you can simply test it with if.

    if (ptr==NULL) {
      "THE LIST DOESN'T EXIST" 
    } else {
      "THE LIST MUST EXIST --> SO IT HAS BEEN ALLOCATED"
    }
    

    I don't know how your programme is written, but you surely understand what am I trying to point out. If it is possible to check like this your allocation and then pass your arguments to you function, you could have a simple solution.

    Of course you must be careful to have your functions with allocating and creating the structure done well but where in C you don't have to be careful.

提交回复
热议问题