Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just wonder that the compiler doesn't throw exception when I use non allocated space , here is a code for example:

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

int main()
{
   int i, n;
   int *a;

   printf("Number of elements to be entered:");
   scanf("%d",&n);

   a = (int*)calloc(n, sizeof(int));
   printf("Enter %d numbers:
",n);
   for( i=0 ; i < n ; i++ ) 
   {
      scanf("%d",&a[i]);
   }

   printf("The numbers entered are: ");
   for( i=0 ; i < n ; i++ ) 
   {
      printf("%d ",a[i]);
   }
   free( a );

   return(0);
}

if n=3 for example and I statically said:

a[10]=3;

it will work and doesn't throw exception and I can print it, so what is the impact of using an element out of bound ? and is there a way to know the size ? because (sizeof) wont work on the calloc array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

Accessing data out of bounds gives you undefined behavior, which means anything can happen.

If you go far out of bounds, segmentation faults are to be expected due to accesses to unmapped or protected memory pages. However that assumes a somewhat straightforward mapping of your code to machine code.

The truth is, the compiler only gives you the illusion that your code maps straightforwardly to machine code. The moment you break the rules by causing undefined behavior, the illusion may break in some very bizarre ways and that's what undefined behavior is all about.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...