-4

I made a program in c that uses malloc function. Code:

#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>

int main(){
    int n;
    int *ptr,i,sum;
    sum = 0;
    printf("Enter the number = ");
    scanf("%d",&n);
    ptr = (int *)(malloc(10));
    for(i=0;i<n;i++){
        scanf("%d",ptr+i);
        sum += *(ptr+i);
    }
    printf("The sum of the numbers is = %i",sum);
}

I have used malloc function to allocate a memory of 10 bytes .How is it possible that 10 integers are stored in 10 bytes....

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
Sahib Navlani
  • 68
  • 1
  • 12

1 Answers1

1

It is possible by luck.

You write outside the allocated area and consequently your program has UB (Undefined Behavior).

However, the program may appear to work in some situations but in general it may crash at any time.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63