Checking if a pointer is allocated memory or not

前端 未结 18 1462
伪装坚强ぢ
伪装坚强ぢ 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:59

    No, in general there is no way to do this.

    Furthermore, if your interface is just "pass a pointer to a buffer where I will put stuff", then the caller may choose not to allocate memory at all, and instead use a fixed size buffer that's statically allocated or an automatic variable or something. Or perhaps it's a pointer into a portion of a larger object on the heap.

    If your interface specifically says "pass a pointer to allocated memory (because I'm going to deallocate it)", then you should expect that the caller will do so. Failure to do so isn't something you can reliably detect.

提交回复
热议问题