-6

Case 1: When I take string input, it successfully gives the output, writing this piece of code:

#include <stdio.h>
int main()
{
    char *str;
    scanf("%s",&str);
    printf("%s",&str);
    return 0;
}

Case 2: On the other hand, it throws a Runtime Error for this snippet:

#include <stdio.h>
int main()
{
    char *str;
    scanf("%s",&str);
    printf("%s",str);
    return 0;
}

I found this thing peculiar, and want to know why it happens... Thanks in advance.

  • 5
    Read about **strings**, **pointers**, **arrays** and **dynamic memory allocation** together with **format specification**. Add cherry on cake by reading about *undefined behavior*. – haccks Nov 30 '16 at 22:09
  • 1
    Something around here is lacking memory and that is `str`. – Ed Heal Nov 30 '16 at 22:10
  • Aside from the fact that you didn't allocate memory for `str`, case 2 is the correct implementation. Add a `str = malloc(50);` or similar before using it. You are getting lucky in case 1 and just blasting some memory that doesn't belong to you. – eddiem Nov 30 '16 at 22:11
  • Assume for a moment that case 1 is right. What makes you think that in case 2 you don't need to use `&` - case 1 and case 2 can not both be right. You can't just make it up as you go along. You need to use the correct types. – John3136 Nov 30 '16 at 22:12
  • thank you everyone, i appreciate your answers and will get myself rectified – Uddalak Bhaduri Nov 30 '16 at 22:28
  • @eddiem, neither of the implementations is correct. Even if there were any memory associated to str, you would pass str to scanf(), not &str. – andreee Dec 11 '16 at 12:51

1 Answers1

2

None of those two cases are right.

Case 1 only worked because you got lucky, probably by giving a short string as input. Try something like "bfjabfabjkbfjkasjkvasjkvjksbkjafbskjbfakbsjfbjasbfjasbfkjabsjfkbaksbfjasbfkja" and you'll suffer a seg fault, most likely.

You should have a block of memory associated with str, either on the stack by declaring an array for it or on the heap malloc'ing memory for it.

And you shouldn't use the & operator.

So it would go like this:

#include <stdio.h>
int main()
{
    char str[50];   // 50 is arbitrary
    scanf("%s",str);
    printf("%s",str);
    return 0;
}

or like this:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char* str = malloc(50);   // 50 is arbitrary
    scanf("%s",str);
    printf("%s",str);
    free(str);
    return 0;
}
yLaguardia
  • 585
  • 3
  • 7