Taking string input in char pointer

the char pointer is not initialized, you should dynamiclly allocate memory to it,

char *s = malloc(sizeof(char) * N);

where N is the maximum string size you can read, And its not safe to use scanf without specifying the maximum length for the input string, use it like this,

scanf("%Ns",s);

where N same as that for malloc.


It's undefined behaviour as the pointer is uninitialized. There's no problem with your compiler but your code has problem :)

Make s point to valid memory before storing data in there.


To manage buffer overflow, you can specify the length in the format specifier:

scanf("%255s", s); // If s holds a memory of 256 bytes
// '255' should be modified as per the memory allocated.

GNU C supports an non-standard extension with which you don't have to allocate memory as allocation is done if %as is specified but a pointer to pointer should be passed:

#include<stdio.h>
#include<stdlib.h>  

int main() {
  char *s,*p;

  s = malloc(256);
  scanf("%255s", s); // Don't read more than 255 chars
  printf("%s", s);

  // No need to malloc `p` here
  scanf("%as", &p); // GNU C library supports this type of allocate and store.
  printf("%s", p);
  free(s);
  free(p); 
  return 0;
}

Tags:

C