简体   繁体   English

在取消引用之前为未初始化的指针赋值

[英]Assigning value to unintialized pointer BEFORE dereferencing

I found a code snippet where a char pointer (say *pData) is declared without being initialized to NULL.我发现了一个代码片段,其中声明了一个字符指针(比如 *pData)而没有被初始化为 NULL。

char *pData, *pData2;
char string[10] =  "Hello"
pData2 = &string[0];
SomeFuntionToAssignValue(pData2, &pData);

SomeFuntionToAssignValue(char *pData2, char **pData)
{
    if (something)
    {
        *pData = pData2;
    }
    else if (something)
    {
        *pData = &pData2[some calculation]
    }
}

Can dereferencing pData, after calling function SomeFuntionToAssignValue(), at any point of time throw a "memory access exception" error?可以在调用函数 SomeFuntionToAssignValue() 后取消引用 pData,在任何时间点抛出“内存访问异常”错误吗?

Because during compilation or local-testing(here testing is done in targets which can be reloaded at any point of time so usually the chances of memory corruption decreases) we didn't face any "memory access exception" error.因为在编译或本地测试期间(这里测试是在可以随时重新加载的目标中完成的,因此通常内存损坏的机会会降低)我们没有遇到任何“内存访问异常”错误。

But during testing in the field environment, where the target was not reloaded for at least a week's time, a "memory access exception" error was thrown.但是在现场环境中测试时,目标至少一周没有重新加载,抛出了“内存访问异常”错误。

So, is there any chance that NOT doing char *pData = NULL could have caused the "memory access exception" error?那么,不执行char *pData = NULL是否有可能导致“内存访问异常”错误?

Yes, there is a chance, because your SomeFuntionToAssignValue doesn't always assign to *pData .是的,有机会,因为您的SomeFuntionToAssignValue并不总是分配给*pData And initializing pData to be null could prevent a problem because other code might be checking for NULL but can't check for its uninitialized value.pData初始化为 null可以防止出现问题,因为其他代码可能正在检查NULL但无法检查其未初始化的值。 But that all depends on code you haven't shown;但这一切都取决于您尚未显示的代码; there's nothing wrong with this pattern in general.一般来说,这种模式没有任何问题。

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

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