Errors using fclose() [closed] - c

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.

Related

Why I am getting this output?output = 012345 [closed]

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.

sprintf leaves out double data C [closed]

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 11 months ago.
The community reviewed whether to reopen this question 11 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
The sprintf function is not including the variables which I have included.
I have the following code:
typedef struct
{
double sensor_1;
double sensor_2;
double sensor_3;
double sensor_4;
int32_t acc_count;
}PAC1934_ResultData_t;
here is the struct for the power sensor.
PAC1934_ResultData_t power;
power = PAC1934_read_Power_accumulation();
uint8_t buf[100] = {0};
sprintf((char*)&buf, " %010.9f W %010.9f W %010.9f W %010.9f W \n\r",
power.sensor_1, power.sensor_2, power.sensor_3, power.sensor_4);
But the value of buf is always just some spaces and the W. I checked in the debugger and the values of power.sensor_1, ... are always correct and are non zero.
The power values are all of the type double.
The function PAC1934_read_Power_accumulation(); returns a element of type PAC1934_ResultData_t with values for all the elements of it.
What is going wrong?
When I am rewriting the code with an integer, the sprintf works fine.
EDIT: Simple code just trying to output a float or a double doesn't work. Only integer output works. I have tested it with
double test = 1.432;
printf("%f",test);
Candidate problems:
No FP support #Tom V
Various compilers/linkers do not include floating point (FP) support automatically. Code with only FP via printf()/scanf() gets fooled into thinking no FP support needed. Research your compiler to force linking of FP support or maybe simple and some obvious FP code to your source code.
Buffer overrun
sprintf((char*)&buf, " %010.9f W ... may overrun. Is is good practice to be prepared for unexpected FP values and insure no overrun, not matter what. buf[100] with %010.9f is not enough.
Alternatives: #SparKot
// Limit buffer writing
snprintf((char*)&buf, sizeof buf, " %010.9f W ...
// or
// Use `%g` to avoid long text
sprintf((char*)&buf, " %010.9g W ...
// or
// Increase buffer size to some worst case - think -DBL_MAX
uint8_t buf[4 * 350] = {0};
True failure? #M.M
OP only described a failure, but did not post the code that could replicate it.
General help
Enable all compiler warnings.

C program execution success apparently depends on file name [closed]

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.

C programming-In the below program what does '\' means in t[5\] [closed]

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 5 years ago.
Improve this question
#include <stdio.h>
int main(void) {
int i,t[5\];
for(i = 0; i < 5; i++)
t[i\] = 2 * i;
i = 0;
for(i = 0; i < 5; i++)
i += t[i\];
printf("%d",i);
return 0;
}
What does \ in array means? Thanks in advance.
I found this program in CLA (C Programming Language Certified Associate) sample paper.
The program is incorrect, \] is a syntax error.
A possible explanation is the author had to escape some of the C operators (such as [) to typeset code fragments and he also escaped ] which the word processing software seems to leave alone...
Ignore these \ or replace all occurrences of \] with ].
Note that this is a tricky question, and the programmer who wrote this code should be fired.
Note also that the document in question has other errors. For example Question 11 reads:
What happens if you try to compile and run this program?
#include <stdio.h>
int main(void) {
int t[2\][3\] = { { 3, 2, 1 }, { 1, 2, 3} };
printf("%d", sizeof(t) / sizeof(t[1\][1\]));
return 0;
}
A. the program outputs 6
B. the program outputs 3
C. the program outputs 2
D. the program outputs 4
Ignoring the \], the program has potential undefined behavior as %d expects an int but the value passed to printf() has type size_t.
Questions 13, 14, 15, 17 have a similar problem.
It means:
Christopher Boguslawski, President at the C++ Institute,
had failed to have someone properly check over their sample questions for mistakes.
The code will not run the ways it's written.
One could conjecture that they wanted the \ to be at the end of the line (since it's a valid line continuation character) and forgot to put the line feed carriage return in. While that would fix the problem, it doesn't make sense why they'd do that just before every end bracket.
What makes more sense is they probably did a "find and replace" across their whole document and propagated an error by accident.
In speculation: possibly some typesetter wrote all arrays as: t<|5|> (Or some other configuration that made them go back and replace with proper brackets.)
And then in a fit of laziness they did a Find <| Replace [ Which is ok.
And then Find |> Replace \] Which is not ok.
Which kind of makes sense since the \ and ] are right next to each other on the keyboard. (They probably fat fingered it.)
The fact that the whole document has a \ just before every ] is a smoking gun.
So it's most likely a sloppy Find/Replace that deprecated their whole document.
So it means the \ in t[5\] is an error.
The backslash is not allowed in that case, it's invalid syntax.
You can validate it here at ideone online.
You get the following errors:
prog.c: In function ‘main’:
prog.c:4:13: error: stray ‘\’ in program
int i,t[5\];
^
prog.c:7:10: error: stray ‘\’ in program
t[i\] = 2 * i; i = 0;
^
prog.c:11:15: error: stray ‘\’ in program
i += t[i\];
^
If you want to compile the code without errors you just have to remove the invalid \.
Actually you use the backslash as escape character to use it for example in escape sequences like a new line character '\n' which is described here at wikipedia.

C Realloc Memory [closed]

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 6 years ago.
Improve this question
I need to memorize how much memory I allocated with realloc().
Help me
if(!array)
array=(Type*) calloc(1,sizeof(Type));
else
array=(Type*)realloc(array,(cont+1)*sizeof(Type));
array[cont].setName(....);
cont++;
It doesn't work: after firt insert, it say: Access violation
I initialized the cont = 0 in the constructor of my class and freed memory in the destructor.
See the comments added to your code:
int count=0;
if(!array)
array=(Type*) calloc(count,sizeof(Type*); // Problem:
// missing )
// use sizeof(Type)
// calling calloc with count being zero
// so you do not allocate any memory
// use 1 instead of count
array[c].setName(EditName->Text);
c++;
count++;
array=(Type*)realloc(array,count*sizeof(Type*)); // Problem:
// use sizeof(Type)
so it should look:
int count=0;
if(!array)
array=(Type*) calloc(1,sizeof(Type));
array[c].setName(EditName->Text);
c++;
count++;
array=(Type*)realloc(array,count*sizeof(Type));
The variable c must be initialized to zero before running this code
Likewise array must be nullptr before running this code
EDIT
There seem to be one more problem if you intend to run this code several times (which I assume you do).
This line:
array=(Type*)realloc(array,count*sizeof(Type));
^^^^^
Don't use count here as you always sets count to zero
The line shall be:
array=(Type*)realloc(array,c*sizeof(Type));
In general there seems to be no real use of count

Resources