Home > Enterprise >  How to judge whether the incoming buffer is valid in C ?
How to judge whether the incoming buffer is valid in C ?

Time:05-13

In my function, a memory pointer and its size are passed as parameters:

int myFun(uintptr_t* mem_ptr, int mem_size) {
    // Code here
}

Is there any way to tell if this chunk of memory is really valid?

(The Operating System is CentOS Linux release 7.9.2009.)

CodePudding user response:

Don't. Just don't.

Even if you could find a way to check whether the pointer can safely be dereferenced, that doesn't mean it points where you think it does! It might point into your call stack, into your read-only code segment, into the static variables of some library that you're using, or any other place in memory that your program happens to have access to.

The responsibility of passing a valid pointer should be with the caller of the function. To make it harder for the caller to do something stupid, consider passing a std::vector & or std::vector const & instead.

  • Related