Search code examples
cpointersdangling-pointer

Why one method of reading string in C using char* pointer works while other doesn't?


I am reading a string in C using the pointers, through the following two methods, both are exactly same(at least they appear to me). The only difference is in one method I have made a dedicated function to do the job.

Method 1: // Works as expected

#include <stdio.h>

int main()
{
    char *str;
    char delimiter='.';
    int len=0;
    
    scanf("%c",(str+len));
    while(*(str+len)!=delimiter)
    {   
        ++len;
        scanf("%c",(str+len));
    }
    ++len;
    *(str+len)='\0';

    printf("%s",str);

    return 0;
}

Method 2: // Doesn't work, nothing gets printed on the screen

#include <stdio.h>

int readString(char *str,char delimiter)
{
    int len=0;
    
    scanf("%c",(str+len));
    while(*(str+len)!=delimiter)
    {   
        ++len;
        scanf("%c",(str+len));
    }
    ++len;
    *(str+len)='\0';

    return len;
}

int main()
{
    char *str;
    
    int len=readString(str,'.');

    printf("%s",str);

    return 0;
}

I am completely clueless about what I am doing wrong.

While further playing with the code in Method 2, I observed if I just declare a variable(even useless) with initialisation(like int useless=-1;) between lines char *str; and int len=readString(str,'.'); the code works fine.

This added further to my headache.

Can someone explain what is really going on?

My guess is it has to do something with dangling pointers, but then if that was the case Method 1 should have also failed.


Solution

  • In the first code

     scanf("%c",(str+len));
    

    you're trying to write into (access) a memory location which is invalid. Notice that str actually is uninitialized, i.e., it does not point to any valid memory location. So, the program invokes undefined behaviour and the outcome cannot be justified in any way.

    In the second code, the same problem is present, so the behaviour is undefined again.