9

For a unit test of C dode, I want to ascertain that a value passed as a void * is, indeed, a valid pointer.

I don't think that I can prove that it definitely is a valid pointer, but how can I say that it probably is? Or definitely is not?

I am developing and unit testing on a 64 bit Intel processor, and the target is an ARM 9. I am not averse to assembler inserts.

  • is there a minimum value for a valid pointer? 0x08 doesn't look very pointer-ish, wheras values above 0x1000000 do.
  • must it be divisible by something (say 8)?
  • can I say with 100% certainty that an odd number is not a valid pointer?

I don't need a flawless answer, just something to catch most errors.


[Update] I am considering looking at the link map, although that seems like overkill. The problem is occuring when casting to remove compiler wanrings. Some system calls require a char * or void *, and csting to those is masking some coding errors.

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • 3
    What is the OS? – redneb Sep 05 '16 at 08:02
  • Both host & target are LInux, but why woould that matter? – Mawg says reinstate Monica Sep 05 '16 at 08:05
  • 5
    If your function can take any input, you can't tell a thing. For every possible pointer address, there will be a possible integer raw data value. Then you can't even tell if it is "probably a pointer". So without knowing the nature of the function inputs, I don't think this question makes sense. – Lundin Sep 05 '16 at 08:07
  • 4
    For linux, maybe you could look at `/proc/$PID/smaps` to see if the pointer address falls in the of the mapped ranges of virtual memory. – redneb Sep 05 '16 at 08:07
  • 1
    if this can help: http://stackoverflow.com/questions/19255148/c-macro-checking-if-a-variable-is-a-pointer-or-not – Giorgi Moniava Sep 05 '16 at 08:08
  • 4
    https://blogs.msdn.microsoft.com/oldnewthing/20060927-07/?p=29563 – Hans Passant Sep 05 '16 at 08:14
  • 1
    Like Lundin said, there is no way to do this in general. If you want to test such a thing, you need to do unit tests on the caller (i.e. test that all conditions for the caller to pass a valid pointer are met), not try to test within your function that a valid pointer has been passed. – Peter Sep 05 '16 at 08:17
  • 1
    What if you read 1 byte from the address and catch the signal the kernel throws and try to interpret it? That would sort out most of the invalid addresses. – Rad'Val Sep 05 '16 at 08:39
  • 1
    You should ever set to NULL a pointer not valid. It is one of the first "rules" for good programming. Never leave a not initialized pointer around. – jurhas Sep 05 '16 at 09:16
  • 2
    A `char*` pointing into the middle of a string can easily contain an odd address. – Bo Persson Sep 05 '16 at 12:01
  • 1
    @Valentin Radu - that only works if the OS checks the access and signals the program. That is certainly not guaranteed for all possible invalid pointers. – Peter Sep 05 '16 at 14:15

0 Answers0