简体   繁体   English

在图书馆里,我应该检查指针是否有效吗?

[英]In a library, should I check if pointers are valid?

I've wondered this for a while and the necessity of checking whether pointers are valid or not in my own library is even necessary.我想知道这个问题有一段时间了,甚至有必要检查指针在我自己的库中是否有效。 Should I just expect the user to pass in the correct pointers because it's their job if they're using the library?我是否应该只期望用户传递正确的指针,因为如果他们正在使用该库,那是他们的工作?

For example if I have a library which allocates and returns a structure例如,如果我有一个分配和返回结构的库

struct some_context{
    uintptr_t somedata;
};
struct some_context* createsomecontext(void){
    return malloc(sizeof(struct some_context));
}

But then I want to operate on that structture但后来我想对那个结构进行操作

void dosomethingwithsomecontext(struct some_context* ctx){
    //which is more valid here?
    assert(ctx);
    
    //or
    if(!ctx)
        return;
    
    //do something with ctx
}

Does it make more sense to call assert, or check if the structure is valid and return if it isn't?调用断言或检查结构是否有效并在无效时返回是否更有意义? Should I not even bother with checking the pointer and just assume the user is going to do the right thing?我是否应该甚至不去检查指针而只是假设用户将做正确的事情? And same thing with cleanup清理也一样

void destroysomecontext(struct some_context* ctx){
    //Which is more valid?
    assert(ctx);
    
    //or
    if(!ctx)
        return;
    
    //do cleanup
}

What's more appropriate?什么更合适? assert, if,or neither?断言,如果,或两者都不? Similarly if I'm even writing a function to operate on a string?同样,如果我什至写一个 function 来对字符串进行操作?

void dosomestringoperation(char* str){
    assert(str);
    //or
    if(!str)
        return;
    
}

Should libraries ever do these checks?图书馆应该做这些检查吗? At least in user mode, I can understand in the kernel since every device has access to the global memory and can cause a crash by not checking but does that imply even usermode applications should check for security/sanity reasons?至少在用户模式下,我可以在 kernel 中理解,因为每个设备都可以访问全局 memory 并且不检查可能会导致崩溃,但这是否意味着即使是用户模式应用程序也应该出于安全/健全的原因进行检查?

Generally one assumes that pointers are valid, especially given that, except for null pointers, you have no way to tell if a passed pointer is valid for real (what if you are given a pointer to unallocated memory, or to wrong data?).通常人们假设指针是有效的,特别是考虑到,除了 null 指针,你没有办法判断传递的指针是否真正有效(如果你得到一个指向未分配的 memory 或错误数据的指针怎么办?)。

An assert (possibly one that is active even in release builds, though) is a nice courtesy to your caller, but that's just it; assert (尽管可能甚至在发布版本中也是活跃的)对您的调用者是一种很好的礼貌,但仅此而已; you are probably going to crash anyway when trying to dereference it, so whatever.在尝试取消引用它时,您可能无论如何都会崩溃,所以无论如何。

By all means, though, do not silently return if you get a null pointer: you are hiding a logical error under the rug, making it harder to debug for your caller.但是,无论如何,如果您得到一个 null 指针,请不要悄悄返回:您在地毯下隐藏了一个逻辑错误,使您的调用者更难调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM