Checking if a pointer is allocated memory or not

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

    I don't know a way of doing it from a library call, but on Linux, you can look at /proc//numa_maps. It will show all sections of memory and the third column will say "heap" or "stack". You can look at the raw pointer value to see where it lines up.

    Example:

    00400000 prefer:0 file=/usr/bin/bash mapped=163 mapmax=9 N0=3 N1=160
    006dc000 prefer:0 file=/usr/bin/bash anon=1 dirty=1 N0=1
    006dd000 prefer:0 file=/usr/bin/bash anon=9 dirty=9 N0=3 N1=6
    006e6000 prefer:0 anon=6 dirty=6 N0=2 N1=4
    01167000 prefer:0 heap anon=122 dirty=122 N0=25 N1=97
    7f39904d2000 prefer:0 anon=1 dirty=1 N0=1
    7f39904d3000 prefer:0 file=/usr/lib64/ld-2.17.so anon=1 dirty=1 N0=1
    7f39904d4000 prefer:0 file=/usr/lib64/ld-2.17.so anon=1 dirty=1 N1=1
    7f39904d5000 prefer:0 anon=1 dirty=1 N0=1
    7fffc2d6a000 prefer:0 stack anon=6 dirty=6 N0=3 N1=3
    7fffc2dfe000 prefer:0
    

    So pointers that are above 0x01167000 but below 0x7f39904d2000 are located in the heap.

提交回复
热议问题