-1

https://i.stack.imgur.com/kU6lD.png

#include<stdio.h> 
#include<stdlib.h> 
int main() 
{
    int i,n,*a=(int*)malloc(n*sizeof(int)); 
    scanf("%d",&n); 
    for(i=0;i<n;++i) 
    scanf("%d",(a+i)); 
    for(i=0;i<n;++i) 
    printf("%d",*(a+i));
    free(a); 
    return 0; 
}

the above program run smootly till input(i.e. n) is less than or equal to 6.If I input n greater than 6 then it is showing runtime error.WHY?here runtime error depends on value of input??)

m0h4mm4d
  • 400
  • 4
  • 12
  • You are using the value of an uninitialized variable `n` to allocate memory. that `malloc()` need to be put **after** `scanf()`. – m0h4mm4d Aug 06 '17 at 04:14
  • And I suggest you put the code inside your question, instead of uploading it as an image. There is a code tag for it in SO which works perfectly fine for c code. – m0h4mm4d Aug 06 '17 at 04:17

2 Answers2

0

try this at top:

int i = 0;
int n = 0;
int *a = NULL;
scanf("%d", &n);
if(n > 0) {
    a = (int*)malloc(n * sizeof(int));
    if(!a) {
        printf("malloc failed");
        return 0;
    }
}
else {
    printf("enter number > 0");
    return 0;
}
DeyMac
  • 16
  • 2
-1

Welcome to SO. Your program invokes undefined behaviour (UB) when you do malloc(n * sizeof(int)) because the variable n is not initialized and reading / using an uninitialized variable results in UB.

What do you think the value of n will be when you call malloc? n might even be a negative value. Once you invoke UB, there is no telling what your program will do. You should put your call to scanf before you call malloc.

Your main function is not standards complaint. Why? From next time please put your code directly in the question.

babon
  • 3,615
  • 2
  • 20
  • 20