Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for ( ;i<=5;i++)
{
printf ("%d",i);
}
}
Why I am getting this output? output = 012345
I did not expecting any output. because as i didnt intilise i, so from where he is going to start?
if i will be intilise by a undefined value, why I am getting the same output as many times i run the code?
int i;
i is uninitialized and holds an indeterminate value. 0 is one of the many values it can contain.
for ( ;i<=5;i++)
In both i<=5 and i++ you read i that has an indeterminate value. The compiler is allowed to assume that you never do that and may produce assembler code that does anything. The program therefore has what is called undefined behavior.
printf ("%d",i);
Here you print i whatever it may be. If i happened to contain 0 when you left it uninitialized - and if the compiler was "kind" enough to let your failure to initialize i through without producing an executable that crashes (or worse), then the loop will step i from 0 to 6. When it reaches 6, the condition, i<=5, will be false and the loop will end. Only for the values when i is less than, or equal to, 5 will printf ("%d",i); be reached.
Note that the program may do different things when you run it multiple times because it has undefined behavior. i may suddenly be -98723849 when you run the program and then your loop will print the values from -98723849 up to 5.
I did not expecting any output. because as i didnt intilise i, so from where he is going to start?
As mentioned - the program could do just about anything because you didn't initialize i and then read from it. In your case, it seems i contained a 0 and that the program appears to behave as-if you initialized it to 0. Again, this is "pure luck" - no matter how many times in a row it displays the same behavior.
if i will be intilise by a undefined value, why I am getting the same output as many times i run the code?
Because the program has undefined behavior. It may repeat the same thing over and over again for many years. It's a ticking bomb that may suddenly explode one day.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried to run a C source file and the result was it got stuck in an infinite loop. I literally copied and pasted the same code into a new source file, Untitled1, and it ran fine. Both the original and the new source file are saved on the desktop. Why is this happening?
#include <stdio.h>
int main()
{
int i, j, d, a;
scanf("%d %d", &i, &d);
printf("%d\n", i);
a = 1;
while(i>1)
{
i = i%d;
for(j = 1; j<=a; j++)
{
printf(" ");
}
printf("%d\n", i);
d = d/100;
a++;
}
//////////
return 0;
}
Just a simple exercise from CodesDope. The goal is to print
1010101
10101
101
1
Which you get by entering i=1010101 and d=1000000.
I cannot doubt your experience but I'm not sure your conclusion is correct. First we don't run source code, it has to be compiled first. This leaves open the possibility that you have an old executable, i.e. an executable that doesn't reflect the code. The same code compiled the same way should produce the same runtime behavior (given that that code logic is correct).
Since all the variables are integer the d variable can become 0 and if this happens before i becomes less than or equal to 1 the i%d would result in a divide by zero error. Trying your code on repl.it with i = 1000 and d = 77 generates a floating point exception, but different compilers/environments may surface that undefined state differently (though all should produce an error state).
My advice is to delete both your compiled executables and any object files (clean your project), then recompile and compare results. If you still see different behavior based on the same output, then carefully compare your source files (or 'diff' them if you are on a unix'y system). If you still find a discrepancy, update your question with both source files (even if you find them identical), the compiler (name/version) and environment (OS/version) you are using.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a section of code that fails when I try to use fclose to close an output file. The code looks as follows:
void WriteArrayForCheck(int numLines, double **Array) {
char outFile2[300];
sprintf(outFile2, "OutputArray.txt");
FILE *outputFile2;
outputFile2 = fopen(outFile2, "w");
int incRow;
for (incRow = 0; incRow < numLines - 1; incRow++) {
fprintf(outputFile2, "%lf,%lf,%lf\n",
Array[incRow][1], Array[incRow][2], Array[incRow][3]);
}
fclose(outputFile2);
}
I end up with an error related to my executable that says:
free(): invalid next size (normal): 0x0000000001ce1710 ***
and a whole bunch of other stuff that doesn't make sense... The ironic thing is if I comment out the line related to fclose, then the program does not crash and runs perfectly fine... I have not had this issue before. I am sure that my matrices are incremented properly as well. PLease let me know what you think.
The code as posted does not seem to have an obvious problem.
Note however that:
You should always check the return value of fopen() and report failure instead of risking undefined behavior by passing NULL to fprintf and/or fclose.
You should simplify the first few statements as FILE *outputFile2 = fopen("OutputArray.txt", "w");
If you do something more complicated to compute the filename, post it as the problem may lie in seemingly harmless code that you omitted.
The fprintf conversion specifier for double is %f, the l modifier is useless and ignored in this context. It is required in fscanf() to distinguish between float and double, but not needed in fprintf because float values are always passed as double to variable argument functions.
The index values 1, 2 and 3 might be incorrect, arrays are 0 based in C.
Stopping the loop at incRow < numLines - 1 is unexpected too, why omit the last row of the matrix? If you really mean it, a comment would be helpful to clarify why.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have little problem here. Ever since I used srand command I no longer get output I want.
I have to create program that will create array not matter how long.. I chose 5. Then it has to create random numbers into it and 5th number in it has to be 0 and then it has to count all five numbers together. I was sucessful and I did even use some printfs to check if arr[5] is zero. It is. In output I receieve this: 5random numbers (that ones that were created into array) 0 (to check if command where i set arr[5] really set it to zero and result which only count all 5random numbers together but without changing 5th arr into 0. Any ideas why? Thanks!
Code looks like this:
#include <stdio.h>
#include <time.h>
main()
{
srand(time(NULL));
int result,i;
int arr[5];
for (i=0;i<5;i++)
{
arr[i] = rand() % 10+1;
printf("%d ",arr[i]);
}
arr[5]=0;
printf("\n");
printf("%d\n",arr[5]);
i=0;
for(;i<5;i++)
{
result +=arr[i];
}
printf("%d\n",result);
printf("%d\n",arr[5]);
}
The declaration int arr[5] gives an array with five elements numbered from 0 to 4 inclusive. Accessing the 6th element, arr[5], is undefined.
If you want five elements and a "sentinel" (the zero marker), you could define arr as
int arr[6];
You should probably also initialize result to 0 otherwise its value is undefined since it's a local variable (in fact, the meaning of the whole program is, strictly speaking, undefined in this case).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When I compile my C codes sometimes I get this error message.
Mycode.exe has stopped working..
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution available.
My C code :
#include<stdio.h>
main(){
char a;
a="S";
printf("%s",a);
}
So what is the reason for this problem?
Syntax error, Runtime error or another reason?
When you invoke printf with %s it means that printf will start printing at the given address and end when a null terminator is reached, because you are giving printf a char and not a pointer to a char, it tries to use the value written in a to start printing from.
a is a char taking up a space of one Byte while an address is 8 Bytes in a 64 bit system, so basically printf takes the value in 'a' and the the next 7 Bytes(which are random 'garbage') and tries to use it as an address to stop printing.
that is why it sometimes works as you said, sometimes those random addresses are fine to start printing from, but sometimes they are addresses that you are not authorized to access like areas of memory used by the OS or kernel.
to solve the problem you need to make a a char * and not a char, and assign it with a string.
Change your code to
#include<stdio.h>
int main()
{
char a;
a='S';
printf("%c",a);
return 0;
}
and it will work fine.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I read this paragraph in c the complete reference book
C has no bounds checking on arrays. You could overwrite either end of
an array and write into some other variable's data or even into the
program's code. As the programmer, it is your job to provide bounds
checking where needed. For example, this code will compile without
error, but it is incorrect because the for loop will cause the array
count to be overrun.
#include <stdio.h>
int main(){
int count[10], i;
/* this causes count to be overrun */
for(i=0; i<15; i++) count[i] = i;
for(i=0; i<15; i++) printf("%d ",count[i]);
return 0;
}
and when I try the code it gives me
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
And then a run time error was displayed on the screen. The error was
array.exe has stopped working
My question is : What is the type of that error? And does it mean that my IDE checks the bounds of the array?
C doesn't check array idexing, it does only simple pointer-arithmetic. That is, the standard defines the operation array[i] as array + i.
Depending on the resulting memory address of that computation, many things can occur:
The address points to the location of a local variable of the function: You modify the local variable. For example:
int main()
{
int array[10];
int a = 0;
array[11] = 22;
printf(a%i,a); /* Prints 22 */
}
Remember that the point here is that buffer overrun has undefined behaviour. My example could not work, because the compiler is free to reorder the variables layout during compilation, for memory-aligment and optimising purposes.
The address points to the location of a global variable (Thats a very big indexing/jump, but can occur): The effect is the same as in the local variable case.
The address points to the location where the subroutine stores the return address: Many architectures stores the return address of a function in a register, but if the architecture stores it in the stackframe of the function... WOW. TRY TO DEBUG THAT!!! :)
The address goes out of the memory space of the process: Modern operative systems always check memory accesses to prevent this, so when this happens the OS kicks you in the ass and throws an exception.
Finally note that things are only applicable in release compilation. In debug mode the compiler adds a lot of code to check this kind of things to throw (Provide) a comprehensible and easy-debuggeable exception.
For example: When allocating dynamic arrays, windows debug-heap first fills the memory space that will be used with a flag which says that memory space is ready to use, but it doesn't contains any data: Thats the hexspeak 0xBADF00D. After this, malloc retrieves the memory location, adding hexspeaks around the array to provide bounds checking.
See this article for a complete explanation.
The moment the first loop reaches i=10, you enter the realm of undefined behaviour (since you're writing past the end of count). From that point on, anything can happen.
Your IDE had nothing to do with it. The OS killed your program because it tried to access memory that didn't belong to it.
This type of error is usually known as an access violation.
That's fine - and the point of the article you have read...
What you are supposed to do is limit the for loop so that it only runs from 0 to 9.
Or, if you really need 15 items, expand the array to take them...