1

Consider the following. Say you have an char arr[3] , like in the code below. you use fgets(arr, 20, stdin) //20 being any number above 3//; and sscanf() to get an input from the user, then print out the array. sizeof(arr) still implies it's size 3, but it prints out correctly until it reaches 20 characters. how is this possible?also, it doesn't always produce segmentation fault. does it have to bump at already written-in memory block to do so?

summary: -how is it possible that char arr[3] prints out 3+(in fact, as many as we want) chars? -why segmentation fault doesn't always appear when we keep writing to an array that's already reached (and went past) its size?

thank you! Pawel

#include <stdio.h>

int main()
{
    char arr[3];
    int x,y,z;
    fgets(arr, 20, stdin);
    sscanf(arr, "%d, %d, %d,", &x, &y, &z);
    printf("x%i, y%i, z%i\n",x, y, z);
    printf("%s", arr);
    printf("%lu\n", sizeof(arr));
}
Duck Ling
  • 1,577
  • 13
  • 20

0 Answers0