c - Difference between array and malloc -
here code :
#include<stdio.h> #include <stdlib.h> #define len 2 int main(void) { char num1[len],num2[len]; //works fine //char *num1= malloc(len), *num2= malloc(len); int number1,number2; int sum; printf("first integer add = "); scanf("%s",num1); printf("second integer add = "); scanf("%s",num2); //adds integers number1= atoi(num1); number2= atoi(num2); sum = number1 + number2; //prints sum printf("sum of %d , %d = %d \n",number1, number2, sum); return 0; }
here output :
first integer add = 15 second integer add = 12 sum of 0 , 12 = 12
why taking 0
instead of first variable 15
?
could not understand why happening.
it working fine if using
char *num1= malloc(len), *num2= malloc(len);
instead of
char num1[len],num2[len];
but should work fine this.
edited :
yes, worked len 3
why showed undefined behaviour. mean not working normal arrays
, working malloc
. got should not work malloc
also. why worked me, please specific can debug more accurately ?
is there issue system or compiler or ide ?
please explain bit more helpful or provide links resources. because don't want unlucky anymore.
len
defined 2. left no room null terminator. in array case overrun array end , damage stack. in malloc
case overrun heap , potentially damage malloc
structures.
both undefined behaviour. unlucky code works @ all: if "lucky", program decide crash in every case show you triggering undefined behaviour. unfortunately that's not how undefined behaviour works, c programmer, have defensive , avoid entering undefined behaviour situations.
why using strings, anyway? use scanf("%d", &number1)
, can avoid of this.
Comments
Post a Comment