0

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.

deadLock
  • 390
  • 6
  • 16
  • Just declare your string `str` with square brackets like so `char str[100]` or any buffer size you like. This way you are making room for your string to be stored. When you just use a pointer you don't have memory set aside for your string and you can only point to the memory location where your string is stored using a pointer. – Dhruv Vanjari Aug 19 '20 at 12:47

1 Answers1

4

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261