简体   繁体   中英

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.

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?

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?

Yes, there is a chance, because your SomeFuntionToAssignValue doesn't always assign to *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. But that all depends on code you haven't shown; there's nothing wrong with this pattern in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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