Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking string input in char pointer

Tags:

c

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

int main(){
    char *s;
    printf("enter the string : ");
    scanf("%s", s);
    printf("you entered %s\n", s);
    return 0;
}

When I provide small inputs of length up to 17 characters (for example "aaaaaaaaaaaaaaaaa") the program works perfectly fine but on providing inputs of larger lengths, it gives me a runtime error saying "main.c has stopped working unexpectedly".

Is there some problem with my compiler (codeblocks) or my pc (windows 7)? Or is it somehow related to the input buffer of C?

like image 256
Nikunj Banka Avatar asked Feb 05 '13 12:02

Nikunj Banka


3 Answers

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;
}
like image 158
P.P Avatar answered Nov 15 '22 23:11

P.P


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.

like image 8
Rami Jarrar Avatar answered Nov 15 '22 23:11

Rami Jarrar


You are not allocating any memory to the character array so first try to get memory by calling malloc() or calloc(). then try to use it.

s = malloc(sizeof(char) * YOUR_ARRAY_SIZE);
...do your work...
free(s);
like image 1
akp Avatar answered Nov 15 '22 23:11

akp