Shantanu Nandan Shantanu Nandan - 3 months ago 14
C Question

programname.exe has Stopped Working dialog in windows 10

I am using Windows 10 , TDM-GCC with Eclipse NEON development tool which is not able to execute the program after clicking on run button, and I don't get to see any error messages it throws after compilation. It shows the Windows 10 dialog for non executed program, where it says "A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available."

Program which i am trying to run-

#include<stdio.h>

int first;
int second;
int *firstreference;
int *secondreference;

void calledbyvalue(int input);
void calledbyreference(int *input);

void calledbyvalue(int input){

//disabling the buffer
setbuf(stdout, NULL);

printf("Enter the first value - ");
scanf("%d", &input);
printf("Value entered for first is - %d", input);
printf("Entered input is - %d",input);

}

void calledbyreference(int *inputreference){

//disabling the buffer
setbuf(stdout, NULL);

printf("Enter the second value - ");
scanf("%d", &inputreference);
printf("Value entered for second is - %d", inputreference);
printf("Entered input reference value is - %d",&inputreference);

}

void main(){

*firstreference = &first;
*secondreference = &second;

//Calling user defined functions here ....
calledbyvalue(first);
calledbyreference(firstreference);

calledbyvalue(second);
calledbyreference(secondreference);

}

Answer

The part

*firstreference = &first;
*secondreference = &second;

invokes undefined behavior by dereferencing NULL, which is the initial value of static pointer variables with no explicit initialization. Do not do that. To assign pointers to first and second, use

firstreference = &first;
secondreference = &second;

Also the part

scanf("%d", &inputreference);
printf("Value entered for second is - %d", inputreference);
printf("Entered input reference value is - %d",&inputreference);

invokes undefined behavior by passing pointer to object having wrong type to scanf() and passing data having wrong type to printf(). What you want may be this:

scanf("%d", inputreference);
printf("Value entered for second is - %d", *inputreference);
printf("Entered input reference value is - %d",*inputreference);

One more note is that you should use standard int main(void) in hosted environment instead of void main(), which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.