uninitialized local pointer error in code

Viewed 60

Can someone identify why I get this error?

Error C4703 potentially uninitialized local pointer variable 'pw' used
Warning C6001 Using uninitialized memory 'pw'.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char string[] = "Today exam is very easy and fun", le = 'y';
    char* pStr = string, * pw;

    while (*pStr)
    {
        if (pStr == string || *(pStr - 1) == ' ')
            pw = pStr;

        if (*pStr == le && (*(pStr + 1) < 'a' || *(pStr + 1) > 'z'))
        {
            while (pw <= pStr)
                printf("%c", *pw++);
            printf(" ");
        }
        pStr++;
        while ((*pStr < 'a' || *pStr > 'z') && (*pStr < 'A' || *pStr > 'Z') && *pStr)
            pStr++;
    }
    return 0;
}
1 Answers

You define pw without an initialization here:

    char* pStr = string, * pw;

You initialize it (optionally, depending on the value pointed to by pStr) here:

    while (*pStr)
    {
        if (pStr == string || *(pStr - 1) == ' ')
            pw = pStr;

and you use it here, possibly uninitialized (if the above test failed all times before you entered in the code below).


        if (*pStr == le && (*(pStr + 1) < 'a' || *(pStr + 1) > 'z'))
        {
            while (pw <= pStr)
                printf("%c", *pw++);

This is a common error, just initialize it in the declaration as NULL

    char* pStr = string, * pw = NULL;

and later, add a check for NULL before the while loop:

        if (pw != NULL) {
            while (pw <= pStr)
                printf("%c", *pw++);
        }

You need to do, or you can get to the printf above with pw pointing anywhere, and get blocked in the while loop (because pw never gets bigger than pStr) or the loop never executes (because it's already bigger when you face the loop the first time. An uninitialized local variable can have any random value you can imagine, so the compiler checks if you initialize it and warns you in case there's some risk that the variable gets used without a proper initialization. Good for the compiler!!!

Related