The wonder of memory limitation

i tried to use malloc to allocate memory to int array but the array seems never be fulled, it is so werid! I just allocated 1 sizeof(int) to the array,should the input to the array will be terminated when i entered one integer,why the program did not stop due to overuse of memory and can show what i have inputted
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include<stdio.h>
#include<stdlib.h>
int main(){
	int *array,i=0,k,size=1;
	array=(int*)malloc(sizeof(int));
	while(1){
		scanf("%d",array+i);		
		if(*(array+i)==-1)
		break;
		i++;
	}
	for(k=0;k<i;k++){
		printf("%d ",array[k]);
	}

}
You are accessing memory that is outside the memory block that you have allocated for an array. That is out of range error. The result is undefined behaviour. It is your responsibility to make sure that you don't do out of range errors.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<stdio.h>
#include<stdlib.h>
int main(){
	int *array,i=0,k,size=1,input=0,read=0;
	array=(int*)malloc(size*sizeof(int));
	while(i<size){
		read=scanf("%d",input);		
		if(read<1 || input==-1)
		break;
		array[i]=input;
		i++;
	}

	for(k=0;k<i;k++){
		printf("%d ",array[k]);
	}
}
Last edited on
Topic archived. No new replies allowed.