Debug assertion failed fprintf in VS 2010 - c

I'm new in programming and iam from Tver.
There is a problem in program. I don't know where. I am using input file and output file. So, i tried to debug program, but i failed
I'm using a Visual Studio 2010.
Thank you in advance.
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string.h>
using namespace std;
int num[100];
void outc(int s, int ss)
{int i,temp,numb[100],k,l,t;
temp=s; i=0;
while (temp>0)
{
numb[i]=temp%ss;
if (numb[i]>=10) numb[i]='A'-10+temp%16;
temp/=ss;
i++;}
l=i/2; t=0;
i--;
while (i>=l)
{
k=numb[t];
numb[t]=numb[i];
numb[i]=k;
t++;
i--;
}
FILE* fooo;
errno_t errorCodes=fopen_s(&fooo,"output.txt","w");
fprintf(fooo,"s%d= %d\n", ss, numb);
return;
}
int main()
{char c,strbuf[100],num[100];
char *res;
int k,s,i,temp,ost,s2,s8,s10,s16;
FILE* foo;
errno_t errorCode=fopen_s(&foo,"input.txt","r");
fgets(strbuf,1000,foo);
if(strbuf[strlen(strbuf)-1]=='b')
{
strncpy_s(strbuf, strbuf, strlen(strbuf)-1);
c=atoi(strbuf);
k=0;s=0;
while(c!=0)
s+=(c%10)*pow(2,k);
c/=10;
k++;
} else
if(strbuf[0]==0 && strbuf[1]!='x')
{i=0;;
do{
strbuf[i]=strbuf[i+1];
i++;
}while(i!=strlen(strbuf)-1);
c=atoi(strbuf);
k=0;s=0;
while(c!=0)
s+=(c%10)*pow(8,k);
c/=10;
k++;
} else
if(strbuf[0]=='0' && strbuf[1]=='x')
{i=0;k=strlen(strbuf);
do{
strbuf[i]=strbuf[i+2];
i++;
}while(i!=k);
puts(strbuf);
k=0;s=0;
for (i=strlen(strbuf)-1;i>=0; i--)
{
if (strbuf[i]>='A' && strbuf[i]<='F')
c=10+strbuf[i]-'A'; else c=strbuf[i]-'0';
printf("%d\n",c);
s+=c*pow(16,k);
k++;
}
} else s=atoi(strbuf);
printf("%d\n",s);
outc(s,2);
outc(s,8);
FILE* fooo;
errno_t errorCodep=fopen_s(&fooo,"output.txt","w");
fprintf(fooo,"s10= %d\n", s);
outc(s,16);
//if (temp%16>=10) num[len-1]='A'-10+temp%16;
//printf("s2= %d\ns8= %d\ns10= %d\ns16= %d\n", s2, s8, s, s16);
_getch();
return 0;
}

This has numerous issues:
You can't #include <iostream> or have using namespace std in a C program.
There are so many compiler specific things in here that it's going to be hard for most people to help you. You'll make your life a lot easier by writing in standard C. There's no way for me to compile this program to check what's wrong with it, for instance.
Your code is very hard to follow when you use variable names like k, and s, and s2, and the like, and do things like FILE * foo followed by FILE * fooo. Your code is also just formatted horribly.
With strncpy_s(strbuf, strbuf, ...) unless Microsoft is doing something really weird, here, you can't specify the same string as both the source and destination.
strtol() is better here than atoi().
You're not closing any of the files you open, and you're not checking whether they did, in fact, open. Using the & operator here: errorCode=fopen_s(&foo, ... is highly suspicious, but again, you're using some non-standard function, so who knows.
Here: fprintf(fooo,"s%d= %d\n", ss, numb) you tell fprintf() to expect two ints, but the last argument is an array.

Related

How to use the array from another function in main?

Edit: I made some changes at my code.
I want to write a line fitting program by using the data from two .txt file. The code is as following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int data_read(char programs_x[], char programs_y[]) {
int i=0, j=0, k;
int numProgs_x=0;
int numProgs_y=0;
char line_x[1024];
char line_y[1024];
FILE *file_x;
FILE *file_y;
file_x = fopen("data_x.txt", "r");
file_y = fopen("data_y.txt", "r");
while(fgets(line_x, sizeof line_x, file_x)!=NULL) {
//check to be sure reading correctly
//printf("%s", line_x);
//add each filename into array of programs
programs_x[i]=strdup(line_x);
i++;
//count number of programs in file
numProgs_x++;
}
while(fgets(line_y, sizeof line_y, file_y)!=NULL) {
//check to be sure reading correctly
//printf("%s", line_y);
//add each filename into array of programs
programs_y[j]=strdup(line_y);
j++;
//count number of programs in file
numProgs_y++;
}
fclose(file_x);
fclose(file_y);
return 0;
}
int main ( void ) {
int i, j, k, n=1024;
float s1=0,s2=0,s3=0,s4=0,a,d,b;
char programs_x[1024], programs_y[1024];
data_read(programs_x, programs_y);
for(i=0;i<n;i++) {
scanf("%f", &programs_x[k]);
}
for(i=0; i<n; i++){
scanf("%f", &programs_y[k]);
}
for(i=0;i<n;i++) {
s1=s1+programs_x[i];
s2=s2+programs_x[i] * programs_x[i];
s3=s3+programs_y[i];
s4=s4+programs_x[i] * programs_y[i];
}
d=n*s2-s1*s1;
a=(s2*s3-s1*s4)/d;
b=(n*s4-s1*s3)/d;
printf("\nThe values of a and b are : %f\t%f\n",a,b);
printf("\nThe Required Linear Relation is : \n");
if(b>0){
printf("\ny=%f+%fx\n",a,b);
}
else {
printf("y=%f%fx",a,b);
}
return 0;
}
When I try to compile this code, the compiler shows these error:
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
test3.c:
Error E2349 test3.c 22: Nonportable pointer conversion in function data_read
Error E2349 test3.c 33: Nonportable pointer conversion in function data_read
*** 2 errors in Compile ***
How do I fix the errors? Where did I make mistakes in declaring and calling the data types? I'm pretty sure I declare programs_x and programs_y as char this time and not int.
The error is difficulty to pin down as we don't have line numbers but this line is definitely not right in your main:
data_read(char programs_x[], char programs_y[]);
To call a function you just list the variables and values you're passing to it like this:
data_read(programs_x, programs_y);
Which will no doubt cause more errors/warnings to be flagged as you declare programs_x and programs_y as arrays of int, but data_read is expecting arrays of char. So there's a conflict in what you think your function wants and what you're providing to it which you need to sort out.
The error could mean that the non-standard function strdup() is not supported. A C compiler does not need to support it, which is why it is a good idea to avoid that function. If the function is supported as a non-standard extension (it is part of POSIX), you might find it in the header <string.h> which you didn't include.
As for the cause of the rest of the errors, I have no idea, since those appear to originate from other files than the one you posted.

compare string with type of variables

Hello im in need of some help this part of my program is to get a input string like 2x³+2y² and separate it in 2 arrays termos=terms and exp=exponential, however i cant seem to get it working
#include <stdio.h>
#include <math.h>
int main()
{
char poly[50];
int termos[10];
int exp[10];
int contt=0, conte=0, i=0;
char var1, var2, var3;
printf("Introduza o polinómio\n");
scanf("%s", &poly);
for(i=0; i<50; i++)
{
if(poly[i-1]==char && poly[i]==int && poly[i-1]!='+')
{
exp[conte]=poly[i];
conte++;
}
if(poly[i]==int)
{
termos[contt]=poly[i];
contt++;
}
if(poly[i]=='x')
var1=poly[i];
if(poly[i]=='y')
var2=poly[i];
if(poly[i]=='z')
var3=poly[i];
}
Simply impossible, there is not runtime type information in c. Perhaps you should read The XY Problem and ask another question later.
In the line
if(poly[i-1]==char && poly[i]==int && poly[i-1]!='+')
you want to know if poly[i-1] is an alphabetic character, e.g. an 'a', or is a number. You can use the following functions from ctype.h for that:
// among the includes
#include <ctype.h>
// later
if(isalpha(poly[i-1]) && isdigit(poly[i]) && poly[i-1]!='+')
There are more problems in your code. We will post these as comments.

Why am I getting a "Segmentation Fault" error when I try to run the tests?

I've written a function that determines whether or not to assign default values (it assigns default values if the flag is not present, and it assigns values the user passes if the flag is present). And I'm trying to test my function with a string to see if it did give me the right numbers. I keep getting "Segmentation Fault" when I try to run the tests, it compiles, but the tests just don't work. :(
Here's my header file:
#ifndef COMMANDLINE_H
#define COMMANDLINE_H
#include "data.h"
#include <stdio.h>
struct point eye;
/* The variable listed above is a global variable */
void eye_flag(int arg_list, char *array[]);
#endif
Here's my implementation file:
#include <stdio.h>
#include "commandline.h"
#include "data.h"
#include "string.h"
/* Used global variables for struct point eye */
void eye_flag(int arg_list, char *array[])
{
eye.x = 0.0;
eye.y = 0.0;
eye.z = -14.0;
/* The values listed above for struct point eye are the default values. */
for (int i = 0; i <= arg_list; i++)
{
if (strcmp(array[i], "-eye") == 0)
{
sscanf(array[i+1], "%lf", &eye.x);
sscanf(array[i+2], "%lf", &eye.y);
sscanf(array[i+3], "%lf", &eye.z);
}
}
}
And here are my test cases:
#include "commandline.h"
#include "checkit.h"
#include <stdio.h>
void eye_tests(void)
{
char *arg_eye[6] = {"a.out", "sphere.in.txt", "-eye", "2.4", "3.5", "6.7"};
eye_flag(6, arg_eye);
checkit_double(eye.x, 2.4);
checkit_double(eye.y, 3.5);
checkit_double(eye.z, 6.7);
char *arg_eye2[2] = {"a.out", "sphere.in.txt"};
eye_flag(2, arg_eye2);
checkit_double(eye.x, 0.0);
checkit_double(eye.y, 0.0);
checkit_double(eye.z, -14.0);
}
int main()
{
eye_tests();
return 0;
}
The absolute easiest way to solve this one is run it in a debugger. You probably won't even need to learn how to step through your code or anything - just fire up, run, and read the line.
If you are on a *nix system:
Compile your code with -g flag.
Load as, e.g. gdb a.out.
Run now that it's loaded - (gdb) run.
Do whatever you need to reproduce the segfault.
bt or where should give you a stack trace - and an exact line that is causing your problem.
I'm sure enough you can solve it from there to post this as an answer; but if not, knowing the exact line will make it very much easier to research and solve.
The errors are here:
for (int i = 0; i <= arg_list; i++)
{ ///^^
if (strcmp(array[i], "-eye") == 0)
{
sscanf(array[i+1], "%lf", &eye.x);
//^^^
sscanf(array[i+2], "%lf", &eye.y);
sscanf(array[i+3], "%lf", &eye.z);
}
}
i <= arg_list is wrong since you pass in 6, array index starts from 0, the max value is 5
i+1, i+2,i+3 will give you out of bounds index when you iterate from 0 to 5.
Your loop condition is wrong. It should be i < arg_list.
Think about what happens when i == arg_list.

Why does this code crash when I declare one more variable?

Here's my code. It works when I comment out the "luetut" variable.
But when I compile as follows, I get segmentation fault when the program should print the variables. What sense does this make? When I try to make a debug build, something totally weird shows up (multiple definition of this and that).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rakenne
{
int luku;
float liukuluku;
char* mjono;
} Rakenne;
int main(int argc, char *argv[])
{
int luetut = 0;
Rakenne palikka;
// Rakenne palikka, *palikkaosoitin;
// palikkaosoitin = &palikka;
// while(luetut < 1)
// {
printf("Anna luku:\n");
scanf("%d", &palikka.luku);
// } luetut = 0;
// while(luetut < 1)
// {
printf("Anna liukuluku:\n");
scanf("%f", &palikka.liukuluku);
// } luetut = 0;
printf("Anna merkkijono:\n");
scanf("%s", palikka.mjono);
printf("%i\t%.3f\t%s\n", palikka.luku, palikka.liukuluku, palikka.mjono);
return 0;
}
So, is my gcc compiler broken or what could be the problem?
scanf("%s", palikka.mjono);
You didn't make mjono point to anything so writing to it is of course illegal - undefined behavior. Doing something like this leads to erratic behavior: the program "works" or "fails" for no apparent reason.
So, is my gcc compiler broken or what could be the problem
It's rarely constructive to think the tools you are using are the problem.
Expanding on cnicutars answer, the fix would be to allocate some memory for palikka.mjono.
Something like this:
#define SIZE 40 // or whatever you need.
palikka.mjono = malloc( sizeof(char) * SIZE );
Then later don't forget to free that memory:
free( palikka.mjono );
Or if you know what the maximum size of your strings will be, just define your structure as:
typedef struct rakenne
{
int luku;
float liukuluku;
char mjono[SIZE];
} Rakenne;

Segmentation fault happened while calling a correct function

I am solving a 0-1knapsack problem.
I solved the problem by brute force algorithm.
In main.cpp
int main(int argc, char *argv[])
{
......
int solution;
solution = bruteForce();
......
}
The strange thing is, when I implement the bruteForce() in main.cpp, my program works correctly, however, after I move the bruteForce() to bruteForce.cpp and included it in main.cpp, the program will produce segmentation fault when calling the bruteForce().
Here's how I move bruteForce() to bruteForce.cpp.
First I created a header functions.h(because I want to solve the problem by other method after implement brute force successfully)
functions.h:
#include "global.h"
int bruteForce();
int multiplication( int );
And then I move bruteForce() to bruteForce.cpp
#include <iostream>
#include <stdlib.h>
#include <vector>
#include "global.h"
#include "functions.h"
using namespace std;
int bruteForce()
{
int bestValue = 0;
int j, tempSize, tempValue;
int bestChoice[n+1];
for(int i=0; i<multiplication(n); i++)
{
tempSize = 0;
tempValue =0;
j = n;
while(x[j]!=0 && j>0)
{
x[j] = 0;
j--;
}
x[j] = 1;
for(int k=1; k<=n; k++)
{
if(x[k] == 1)
{
tempSize += size[k];
tempValue += value[k];
}
}
if((tempValue > bestValue) && (tempSize <= S))
{
bestValue = tempValue;
for(int p=1; p<=n; p++)
bestChoice[p] = x[p];
}
}
for(int p=1; p<=n; p++)
x[p] = bestChoice[p];
return bestValue;
}
In global.h, I declared some glabal variables:
#include <vector>
using std::vector;
static int n, S;
static vector<int> value, size, x;
The gdb debugger shows
Program received signal SIGSEGV, Segmentation fault.
0x08049308 in main()
Any idea about why this happens?
Thanks in advance.
Oh BTW, if you need more info, here's the package.
You can first type make in the root of this package. Then type this to execute.
./bin/01knapsack -BF inputs/n5S11.in n5s11.out
You shouldn't put your variables in a header file. When you include that from both your source files, both will get their own individual copy of that variable - and thus you wont be able to transfer data between your functions in the way you think (or at least, that's my understanding of how it should work - I'll admit that I'm not 100% sure what actually happens).
The best way to transfer data to a function is to use parameters though. Call the function with whatever it needs, and return data either through the function return value, or through a pointer or reference parameter. Using global variables for stuff like this is error prone (as you have seen), and it's much less clear for others looking at your code.
If you absolutely want to use global variables, declare them in one of your source files, and put them in your global header file with an extern statement in front of it. When you then include the header from another file, extern tells the compiler that it shouldn't actually create the variable itself, but rather that it is provided by another object file.
So, in main.cpp:
int n, S;
vector<int> value, size, x;
And in global.h:
extern int n, S;
extern vector<int> value, size, x;

Resources