0
#include <stdio.h>

int main()
{
char *a,*b;
scanf("%s %s",a,b);
printf("%s %s",a,b);
return 0;
} 

It works like this,

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

I think its something with memory becoz when i use malloc and assign some memory it works.

  • 4
    The `scanf` function doesn't, and can't, allocate memory for the strings. It just uses the uninitialized pointers you pass, to write the strings somewhere. That leads to *undefined behavior*. In *both* cases. – Some programmer dude Feb 16 '23 at 12:42
  • 1
    *"when i use malloc and assign some memory it works"* yes because you have to allocate memory you point to. Your test code working without that is pure accident. Search for *C++ memory tutorial* or similar to teach you the basics. Don't use pointers until you have learned what they do. – Peter Krebs Feb 16 '23 at 12:45
  • @PeterKrebs Why suggest a C++ memory tutorial instead of a C memory tutorial? :) – Harith Feb 16 '23 at 13:07
  • Oh sorry I typed C++ out of reflex - thanks for pointing it out. Mmh can't edit the comment though ‍♂️ – Peter Krebs Feb 16 '23 at 13:10

1 Answers1

3

It is undefined behaviour (UB) in both cases as you pass the pointer which was not assigned with reference to the allocated valid memory, large enough to accommodate the scanned strings. As it is a UB it does not have to express itself in any particular way. So single variable version does not work as well.

int main(void)
{
   char x[10], y[10];
   char *a = x,*b = y;
   /* .... */
}
int main(void)
{
   
   char *a = malloc(10),*b = malloc(10);
   /* .... */
   free(a);
   free(b);
}
int main(void)
{
   char a[10], b[10];
   /* .... */
}
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0___________
  • 60,014
  • 4
  • 34
  • 74