-8

I allocates memory using malloc(1) i.e it allocated one byte but it accept number more than of 1 byte. Here in this code it accept 1000 number and it is not possible to store this number in 1 byte. code:

#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
int main()
{
    int *a; 
    a=(int *)malloc(1);
    for(int i=0;i<1000;i++)
    {
        a[i]=i;
    }
    for(int i=0;i<1000;i++)
    {
        cout<<""<<a[i];
    }
}

why this happen?

8
  • 2
    There is nothing stopping you from doing undefined behaviour, it has nothing to do with malloc Commented Apr 7, 2017 at 8:50
  • 8
    please don't spam tags. this has nothing to do with java. Commented Apr 7, 2017 at 8:50
  • Neither C nor C++ have bounds checking. If you go out of bounds of allocated memory you have undefined behavior. End of story. I know there are exact duplicates of this question here, if you just search a little. Commented Apr 7, 2017 at 8:51
  • Please try 10000000 instead of 1000. Commented Apr 7, 2017 at 8:54
  • 1
    @AjayBrahmakshatriya making the change will produce a segmentation fault. Which in-turn exemplifies the existence of the error Commented Apr 7, 2017 at 9:09

2 Answers 2

2

It's undefined behavior because C and C++ doesn't actually do any boundary checking with regards to arrays.

Sign up to request clarification or add additional context in comments.

Comments

0

arrays don't have any boundary check conditions. if your OS or the framework is much efficient it will throw segmentation fault.

1 Comment

this should have been a comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.