1
#include<stdio.h>
#define SIZE 3
int main() 
{
char *arr[5];
for(i = 0; i < 5; i++) {
arr[i] = (char *)malloc(SIZE * sizeof(char));
scanf("%s",arr[i]);
}
for(i = 0; i < 5; i++) {
printf("%s",arr[i]);
}
return 0;
}

In the above code i am scanning more than 3(SIZE) characters but it is working fine.what is the issue?

Embedded_User
  • 211
  • 2
  • 12

2 Answers2

0

It is undefined behavior. In linux, doesn't strictly follows the array out of bounds. If there is a free memory it will allow you to access that memory. Refer this link.

In windows, it will strictly follow the array out of bounds. In linux, we have make sure that we are not accessing the out of memory.

Community
  • 1
  • 1
Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
0

Yes it works but it is not safe. arr[i] is just an address in RAM when you do scanf("%s",arr[i]); The characters read will be stored sequentially into the adress starting from pointed out by arr[i].

Lets say you had a memory of 100 chars when you did malloc you may get addresses 10, 20, 30, 40 and 50. Even when you read 5 characters into each of these starting addresses it works. But in case if malloac returns address pointers to 10, 13, 16, 19 and 22. When you do scanf("%s",arr[0]); with 5 chars say 'abcde' the string will be stored in locations from 10 to 15 (one for \0). When you do scanf("%s",arr[1]); with input 'fghij' it will start writing from location 13. Now if you do printf on arr[0] you will get abcfghij.

This behavior depends on the compiler.

Dheerendra Kulkarni
  • 2,728
  • 1
  • 16
  • 18