-3
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char s[100000];
    cin>>s;
    cout<<strlen(s);
    return 0;   
 }

In this Program,character array takes input upto length 4095. Bigger than this length it does not take input. Please provide reason for this problem.

  • 1
    Your stack is probably to small to allocate such big char array. Use `std::string` and `getline()` to get _unlimited_ sized input. – πάντα ῥεῖ Jul 07 '15 at 10:44
  • 1
    Not strictly unlimited. There is an upper limit that depends on available memory (which may be physical, virtual, and/or subject to system quotas), how memory is addressed (e.g. 32-bit vs 64 bit), how memory is allocated (`std::string` requests memory from an allocator, and different allocators use different allocation strategies). All of those factors, and more, interact ..... – Peter Jul 07 '15 at 11:14
  • I used getline() but it create same problem – Tez Hudda Jul 07 '15 at 11:22
  • How are you generating the standard input? Can you prove it's not terminating after 4k, or containing whitespace? You do realise the `>>` reads whitespace-delimited values, don't you? – Tony Delroy Jul 07 '15 at 11:25
  • Related / possible duplicate - [Read a string of length greater than 4096 bytes from stdin in C++](http://stackoverflow.com/questions/22886167/read-a-string-of-length-greater-than-4096-bytes-from-stdin-in-c). – Bernhard Barker Jul 07 '15 at 11:33

1 Answers1

1

When you declare char s[MAX_SIZE] locally, then it gets stored in the stack area, which has limited amount of memory associated with it.

But, if you declare it globally, then it's size can be increased nearly to the remaining memory left in your PC. or use std::string instead to get rid of MAX_SIZE issue.

surajs1n
  • 1,493
  • 6
  • 23
  • 34
  • You should get some sort of stack overflow error from this, not have the program work but just read partial input (or is a stack overflow undefined behaviour?). – Bernhard Barker Jul 07 '15 at 11:41
  • 1
    @Dukeling a stack overflow *is* undefined behaviour. – Quentin Jul 07 '15 at 11:45
  • Either way, [the post I linked to](http://stackoverflow.com/questions/22886167/read-a-string-of-length-greater-than-4096-bytes-from-stdin-in-c) in a comment on the question points out a more likely root cause for this. – Bernhard Barker Jul 07 '15 at 11:47
  • @Quentin I was trying to find proof one way or the other, but didn't have much luck. Do you have a reference for that? – Bernhard Barker Jul 07 '15 at 11:54
  • @Dukeling now that I think of it, a stack overflow probably isn't formally UB, because the Standard does not define what a "stack" is. In practice, it is : a stack overflow just overwrites whatever is there. It may thrash your heap, some other memory, or fall off of your process' address space and segfault. – Quentin Jul 07 '15 at 12:04