Uddalak Bhaduri Uddalak Bhaduri - 9 days ago 6
C Question

Unexpected output of printf for a string in C

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.

Answer

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;
}