-1

This is what I wrote to check if input is a positive integer

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

int isInt(char num[3]) {
    int l = strlen(num);
    int x;

    for ( x = 0; x < l; x++) {
        if ( ! isdigit(num[x]) )
            return 0;        
    }

    return 1;
}

int main(void) {
    int i;
    char str[3];

    printf("Enter a positive integer: ");
    scanf("%s", str);
    if ( isInt(str) == 1 ) {
        i = atoi(str);
        printf("%d \n", i);
    } else {
        printf("This is not a positive integer! \n");
    }

    return 0;
}

And I found some unexpected behaviors, even though the program seems to work:

  1. Whether I #include <ctype.h> or not it makes no difference. How can isdigit() function work without its library? (I'm on ubuntu 14.04 using gcc 4.9.3)

  2. if I impose str to be a a string of length 3 how is it possible that when I run ./a.out it checks correctly and prints also numbers bigger than 999? If I input 5678 shouldn't str only save 567? Or maybe it saves the first 2^3 digits? I'm confused

  3. if I want to check if a string is a positive integer but the number could be very big, how big should str be? Isn't there a way to make it as big as needed?

6
  • 2
    It's better to ask one question per time. And most of your questions have their duplicate asked before, search the site first.
    – Yu Hao
    Jul 19, 2016 at 10:29
  • 2
    Out-of-bounds write, undefined behavior.
    – EOF
    Jul 19, 2016 at 10:29
  • code build is not in your favor, as out of bound is giving working result.
    – Dayal rai
    Jul 19, 2016 at 10:33
  • You can use dynamic memory allocation, and realloc() as necessary.
    – machine_1
    Jul 19, 2016 at 10:34
  • int l = strlen(num); is wrong should be size_t l = strlen(num); also scanf("%s", str); should be scanf("%2s", str);
    – Michi
    Jul 19, 2016 at 10:58

2 Answers 2

2
  1. A header file is not a library; it only says how to use a library. If you omit the header file then the compiler will have to guess what parameters the functions take, but if it guesses right (or close enough) then all may appear to work fine. (Actually it doesn't "guess"; there are rules, of course.)

  2. You didn't "impose" a limit on the length of str, you reserved 3 bytes of space. If you overrun that reservation then the program may (or may not) continue to work fine, but you might find other data has unexpectedly been corrupted. There's no reliable way to predict what data will get overwritten; it's undefined.

  3. No, there's no way to know how big the number will be before the user enters it, but you can set the maximum number of character that will be read by using %3s, for example. However, you need to make sure you reserve enough space for the '\0' nul-character terminator at the end of the string. You can also use an alternative to scanf to read the data in chunks, but you're probably safest just to use a "large" buffer and the maximum field width. Note that scanf can read numbers directly without you reading it as a string and then converting it yourself.

1

Regarding point 3:

No, there is no way to know in advance.

However, it is easy to make a function that reads the input in smaller portions and concatenates them into a big buffer. The big buffer will be allocated dynamically so it can grow when need. The user must call free.

Here is one implementation:

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

#define INCREMENT_SIZE 20
#define SMALL_SIZE 10

char* read_long_string(void)
{
  char* all;
  char* tmp;
  int all_size;
  char some[SMALL_SIZE];

  all_size = INCREMENT_SIZE;
  all = malloc(all_size);
  if (!all)
  {
    // Out of mem
    return NULL;
  }
  all[0] = '\0';

  while(1)
  {
    // Make sure "all" has room for all bytes in "some"
    while(all_size - strlen(all) < sizeof(some))
    {
      all_size += INCREMENT_SIZE;
      tmp = realloc(all, all_size);  // Allocate more memory
      if (!tmp)
      {
        // Out of mem
        free(all);
        return NULL;
      }
      all = tmp;
    }

    // Read bytes into "some"
    if (!fgets(some, sizeof(some), stdin))
    {
      // Error
      free(all);
      return NULL;
    }

    if (strlen(some) > 0)
    {
      // Add the bytes to "all"
      strcat(all, some);

      // Check if newline has been pressed
      if (some[strlen(some)-1] == '\n')
      {
        // done
        return all;
      }

    }
  }
}


int main(int argc, char const *argv[])
{
  char* s;

  printf("Enter a positive integer:\n");
  s = read_long_string();
  if (s) printf("%s", s);

  free(s);

  return 0;
}
3
  • Calling strlen() on an uninitialized malloc()ed buffer is not a good idea.
    – EOF
    Jul 19, 2016 at 16:12
  • Well, it's still a ridiculously convoluted Rube-Goldberg-Schlemiel contraption, but I suppose it's technically correct now.
    – EOF
    Jul 19, 2016 at 17:15
  • @EOF - If you know a better solution to the problem, please post it. That will be more helpful than just calling another solution "ridiculously convoluted" Jul 19, 2016 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.