-2
void loop(char * a){
  for(int i=0;i<10;i++){
    printf("%s\n", a);
  }
}

int main(){
  char str[] = "";

  printf("input:");
  scanf("%[^\n]s", str);

  loop(str);

  return 0;
}

There's nothing wrong when I input short string, but the problem is that when I input longer string.

For example,

input:abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

abcdefghijkl

input:

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

abcdefghijklm

exited, segmentation fault

Why does this error occur? Is this related to buffer overflow?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
L-IKEA
  • 7
  • 1

2 Answers2

2

You invoked undefined behavior by writing to out-of-range to the 1-element array str, allowing anything to happen.

Allocate enough buffer and limit the maximum length to read to avoid buffer overflow.

int main(){
  char str[102400] = ""; /* allocate enough size */

  printf("input:");
  scanf("%102399[^\n]s", str); /* limit the length to read (the size of buffer minus one for terminating null-charater) */

  return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Telling rookies to allocate 102400 bytes on the stack isn't great advise, however... You might want to edit that to a lower size. – Lundin Feb 25 '21 at 13:58
2

The way you define str:

char str[] = "";

It is exactly big enough to contain a zero-length string, i.e. it's an array of length 1. So any larger string that you try to write to it will overrun the buffer, triggering undefined behavior.

You should give your buffer a size that will be large enough to accept the size of string you'll expect.

char str[100];

And update the scanf call to limit the number of characters:

scanf("%99[^\n]s", str);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Ok I got it, but what if I'm not sure how large the input would be? – L-IKEA Feb 25 '21 at 13:57
  • @L-IKEA [c - How can I read an input string of unknown length? - Stack Overflow](https://stackoverflow.com/questions/16870485/how-can-i-read-an-input-string-of-unknown-length) – MikeCAT Feb 25 '21 at 13:59
  • @MikeCAT Thanks a lot! I wonder if the rookie (like me) could come up with such complicated way. – L-IKEA Feb 25 '21 at 14:04