Thread: What's wrong with this C code?

  1. #1
    Registered User
    Join Date
    May 2018
    Posts
    11

    What's wrong with this C code?

    It takes a string input then terminates.
    I can't declare initial size of string array as that depends on the user input and that can be of 10^50 size. What should i do?

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

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > I can't declare initial size of string array as that depends on the user input and that can be of 10^50 size.
    Well 10^50 is the approx number of atoms in the whole of planet Earth.

    > What should i do?
    Move to a much larger planet, where you have the resources to create a machine capable of holding 10^50 bytes of information.

    Seriously though, you can't just declare a pointer and abandon your responsibility to manage the memory in a C program.

    You HAVE to read the input of unknown size in known size quantities, then allocate memory as you go.
    Code:
    char buff[BUFSIZ];
    while ( fgets(buff,BUFSIZ,stdin) ) {
      // do something with buff, say malloc + strcpy
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What is wrong with the code below?
    By 9jashannon in forum C Programming
    Replies: 5
    Last Post: 04-24-2015, 07:42 PM
  2. What is wrong with my code?
    By mindofpoison in forum Game Programming
    Replies: 2
    Last Post: 12-15-2005, 08:12 PM
  3. What's wrong with this code...?
    By The SharK in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2005, 10:27 AM
  4. Replies: 2
    Last Post: 11-26-2004, 02:00 PM
  5. What is wrong with this code?
    By Tride in forum C++ Programming
    Replies: 7
    Last Post: 10-27-2003, 03:49 PM

Tags for this Thread