C programming - Process terminated with status -1073741510 - c

If I run my code when the const N is higher than a specific value (like 30,000 or more), I get "Process terminated with status -1073741510" and the values in my result.dat are not what it supposed to be.
I've tried to look up possible solutions, I know it's a stack overflow problem, but I can't find out anything about what should I modify in my code in order to work.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define N 5000
//static int nep[N];
int main()
{
srand(time(NULL));
int nap=365, szam=0,ember;
float beta=0.3,gamma=0.7,delta=0.05,valseg;
int dbErzekeny,dbBeteg,dbGyogyult;
int *nep;
nep = (int*) malloc(N * sizeof(int));
if(nep == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
//nep = malloc(N * sizeof(char));
int i,j;
FILE *fp;
fp = fopen("eredmeny.dat", "w");
dbErzekeny=N-1;dbBeteg=1;dbGyogyult=0;
nep[0]=1;
for(i=1;i<N;i++){
nep[i]=0;
}
for(i=1; i<=nap; i++){
for(j=0;j<N;j++){
szam=(rand()%N);
if(nep[szam]==0){
ember=(rand() % N);
if(nep[ember]==1){
valseg=(rand() % 100);
valseg=valseg/100;
if(valseg <=gamma){
nep[szam]=1;
dbErzekeny=dbErzekeny-1;dbBeteg=dbBeteg+1;
}
}
}
if(nep[szam]==1){
valseg=(rand() % 100);
valseg = valseg/100;
if(valseg<= beta){
nep[szam]=2;
dbBeteg=dbBeteg-1;dbGyogyult=dbGyogyult+1;
}
}
if(nep[szam]==2){
valseg=(rand() % 100);
valseg = valseg/100;
if(valseg <= delta){
nep[szam]=1;
dbBeteg=dbBeteg+1;dbGyogyult=dbGyogyult-1;
}
}
}
if(fp!=NULL){
fprintf(fp,"%d; %d; %d; %d; \n",i,dbErzekeny,dbBeteg,dbGyogyult);
}else{
printf("Error!");
}
}
free(nep);
fclose(fp);
return 0;
}

Related

Problem with reload data function and save data function

I'm learning about disjoint dynamic memory, so I'm trying to make my own program. I need someone to help me see my problems and show me how to fix them.
I'm almost done with my program, but still have some problems in my program.
My problem:
my saveData() function and reload() function do not work correctly.
I'm not sure whether the saveData() function does get all the data I need
my reload() function just output it has brought back data from the bin file (in saveData() function) and then exit program with some weird code (ex: 8500241654)
Without the above problem, my program works well. Please check the 3 problems in my program in .h file and .c file
C Program Description:
"You will write a program that will store the information about automobiles. The information is about make, mode, yearBuilt, and cost (use struct). The user will choose from menu what they want to do (add auto, display auto with orders of cost or make, use switch).
When the program begins, if there was a previous data file of automobile information it will be loaded automatically. The program will begin where the user last left off. If there is no previous data file, then the program will ask the user how many automobiles record will be needed and the program will start fresh.
When the program ends, all data will be saved to a bin file. All memory will be released from the heap. "
P/s: thank you so much, and appreciate your help.
<Here is my .h file>
// FUNCTION PROTOTYPES
typedef struct {
char make[50]; // ex: Ford, Honda, Toyota
char model[50]; // ex: Corolla, Camry
int yearBuilt; // ex: 2001, 2022
int cost; // ex: 20500, 8999, 15000
} AUTOMOBILE; // 108 bytes
void addAuto(AUTOMOBILE* a[], int* eSize, int size);
int compareChars(const void* a, const void* b);
void displayAuto(AUTOMOBILE* autos[], int eSize);
void displayMenu();
void freeMemory(AUTOMOBILE* autos[], int size);
int getInt(char m[]);
int getCh(char m[]);
void quitProgram(int* temp);
AUTOMOBILE** reload(AUTOMOBILE* a[], int* eSize, int* size);
void saveData(AUTOMOBILE *a[], int eSize, int size);
void sortByCost(AUTOMOBILE* autos[], int eSize);
void sortByMake(AUTOMOBILE* autos[], int eSize);
// FUNCTIONS
void addAuto (AUTOMOBILE *a[], int* eSize, int size) {
char again = 'N';
char autoMake[50];
char autoModel[50];
do {
if (*eSize == size) {
printf("No room to add more automobile...it is full!\n");
system("pause");
return;
}
printf("\nAdding a new automobile to the array of items\n");
// add make
printf("What is the automobile's make (uppercase first letter, ex: Honda)? ");
scanf("%s", a[*eSize]->make);
// add model
printf("What is the automobile's model (uppercase first letter, ex: Camry)? ");
scanf("%s", a[*eSize]->model);
// add year built
a[*eSize]->yearBuilt = getInt("When was the automobile built (ex: 2022)? ");
// add cost
a[*eSize]->cost = getInt("How much does the automobile cost (ex: 45500)? ");
*eSize += 1;
printf("\nWould you like to add another item? [Y/N]: ");
scanf(" %c", &again);
} while (toupper(again) == 'Y');
} // end addAuto
int compareChars(const void* a, const void* b) {
const char* arg1 = *(const char**) a;
const char* arg2 = *(const char**) b;
return strcmp(arg1, arg2);
} // end compareChars
void displayAuto(AUTOMOBILE *autos[], int eSize) {
char option;
printf("\nChoose your desired order");
printf("\n[C]ost low to high");
printf("\n[M]ake ascending order");
option = getCh("\nEnter option: ");
if (option == 'C' || option == 'c')
sortByCost(autos, eSize);
else if (option == 'M' || option == 'm')
sortByMake(autos, eSize);
} // end displayAuto
void displayMenu() {
printf("\n[A]dd one automobile");
printf("\n[D]isplay all automobiles by");
printf("\n\t[C]ost low to high");
printf("\n\t[M]ake ascending order"); // ascending order: A-Z
printf("\n[Q]uit program\n");
} // end displayMenu
void freeMemory(AUTOMOBILE* autos[], int size) {
for (int i = 0; i < size; i++) {
free(autos[i]);
}
free(autos);
} // end freeMemory
int getCh(char m[]) {
char result;
char badValue = 'F';
// loop until get integer value
do {
badValue = 'F';
printf("%s", m);
scanf(" %c", &result);
// if "result" isn't an alphabet, do the loop again
if (isalpha(result) == 0) {
printf("\nYou must enter a valid character!\n");
badValue = 'T';
} // end If
} while (badValue == 'T');
return result;
} // end getCh
int getInt(char m[]) {
int result = 0;
char badValue = 'F';
// loop until get integer value
do {
badValue = 'F';
printf("%s", m);
if (scanf("%i", &result) != 1) {
printf("\nYou must enter a valid real numeric value!\n");
badValue = 'T';
} // end If
} while (badValue == 'T');
return result;
} // end getInt
void quitProgram(int *temp) {
printf("\nThank you for using program!\n");
*temp = 1;
} // end quitProgram
AUTOMOBILE** reload(AUTOMOBILE* a[], int* eSize, int* size) {
*eSize = 0;
FILE* fp = fopen("binaryDocument.bin", "rb");
if (fp == NULL) {
printf("\nNo information has been reload!\n");
system("pause");
return a;
} // end if
printf("\nI have brought back the previous saved data into the array!\n");
system("pause");
// get the size
fread(size, sizeof(int), 1, fp);
// memory allocation for [size] pointers, [size] * 4 bytes of space
// use the size to allocate the space for the pointer array
a = calloc(*size, sizeof(AUTOMOBILE*));
if (a == NULL) {
printf("Allocation of memory failed...\n");
exit(-1);
}
// go through each one of them, and allocate 108 bytes each and allow these pointers to refer to it
for (int i = 0; i < size; i++) {
a[i] = calloc(1, sizeof(AUTOMOBILE));
if (a[i] == NULL) {
printf("Allocation of memory at autos[%i] failed...\n", i);
exit(-1);
}
}
// get the eSize and use the eSize to reload the array
fread(eSize, sizeof(int), 1, fp);
fread(a, sizeof(AUTOMOBILE*), *eSize, fp);
fclose(fp);
return a;
} // end reload
void saveData(AUTOMOBILE *a[], int eSize, int size) { // PROBLEM HERE
FILE* fp = fopen("binaryDocument.bin", "wb");
if (fp == NULL) {
printf("\nCould not save the information to a binary file\n");
system("pause");
return;
} // end if
fwrite(&size, sizeof(int), 1, fp);
fwrite(&eSize, sizeof(int), 1, fp);
fwrite(a, sizeof(AUTOMOBILE*), eSize, fp);
fclose(fp);
} // end saveData
void sortByCost(AUTOMOBILE *autos[], int eSize) {
int temp = 0;
int autoCost[1000];
for (int i = 0; i < eSize; i++) {
autoCost[i] = autos[i]->cost;
}
for (int i = 0; i < eSize; ++i) {
for (int j = i + 1; j < eSize; ++j) {
if (autoCost[i] > autoCost[j]) {
temp = autoCost[i];
autoCost[i] = autoCost[j];
autoCost[j] = temp;
}
}
}
printf("\nAutomobiles are displayed from low to high in term of cost: \n");
for (int l = 0; l < eSize; l++) {
for (int k = 0; k < eSize; k++) {
if(autoCost[l] == autos[k]->cost)
printf("%i\t%s\t%s\t%i\n", autoCost[l], autos[k]->make, autos[k]->model, autos[k]->yearBuilt);
}
}
} // end sortByCost
void sortByMake(AUTOMOBILE *autos[], int eSize) {
qsort(autos, eSize, sizeof(AUTOMOBILE*), compareChars);
printf("\nAutomobiles are displayed A-Z: \n");
for (int i = 0; i < eSize; i++) {
printf("%s\t%s\t%i\t%i\n", autos[i]->make, autos[i]->model, autos[i]->yearBuilt, autos[i]->cost);
}
} // end sortByMake
<Here is my .c file>
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "DJDMHeader.h"
//****************************************************
// MAIN FUNCTION
int main() {
int size = 0;
int eSize = 0;
AUTOMOBILE** autos = NULL; // create the variable to make the array of automobile pointers
int i, temp = 0;
char choice;
// reload data
autos = reload(autos, &eSize, &size);
// case: nothing to reload, start fresh
if (size == 0) {
// get integer value for variable size
size = getInt("How many automobiles will you have at the most: ");
// memory allocation for [size] pointers, [size] * 4 bytes of space
autos = calloc(size, sizeof(AUTOMOBILE*));
if (autos == NULL) {
printf("Allocation of memory failed...\n");
exit(-1);
}
// go through each one of them, and allocate 108 bytes each and allow these pointers to refer to it
for (i = 0; i < size; i++) {
autos[i] = calloc(1, sizeof(AUTOMOBILE));
if (autos[i] == NULL) {
printf("Allocation of memory at autos[%i] failed...\n", i);
exit(-1);
}
}
}
while (temp == 0) {
displayMenu();
choice = getCh("What is your choice?: ");
// switch
switch (choice) {
case 'a':
case 'A':
addAuto(autos, &eSize, size);
break;
case 'd':
case 'D':
displayAuto(autos, eSize);
break;
case 'q':
case 'Q':
quitProgram(&temp);
break;
default:
printf("\nPlease choose the existed choices!\n");
}
}
// Save data
saveData(autos, eSize, size);
// Free memory
freeMemory(autos, size);
return 0;
}
If anything about my program or my question make you unhappy (or something like that), please tell me, I will edit again. So much thanks.
You either operate on an array:
#include <stdio.h>
typedef struct {
char make[50]; // ex: Ford, Honda, Toyota
char model[50]; // ex: Corolla, Camry
int yearBuilt; // ex: 2001, 2022
int cost; // ex: 20500, 8999, 15000
} AUTOMOBILE;
// array
void saveData(AUTOMOBILE *a, int eSize, int size) {
FILE *fp = fopen("binaryDocument.bin", "wb");
if (!fp) {
printf("\nCould not save the information to a binary file\n");
return;
}
fwrite(&size, sizeof(int), 1, fp);
fwrite(&eSize, sizeof(int), 1, fp);
fwrite(a, sizeof(*a), eSize, fp);
fclose(fp);
}
int main() {
AUTOMOBILE a[] = {
{ "Ford", "Model T", 1908, 1000 },
{ "Honda", "Accord", 2022, 20000 }
};
saveData(a, sizeof(a) / sizeof(*a), 42);
}
or as an array of pointers:
#include <stdio.h>
typedef struct {
char make[50]; // ex: Ford, Honda, Toyota
char model[50]; // ex: Corolla, Camry
int yearBuilt; // ex: 2001, 2022
int cost; // ex: 20500, 8999, 15000
} AUTOMOBILE; // 108 bytes
// array of pointers
void saveData(AUTOMOBILE *a[], int eSize, int size) {
FILE *fp = fopen("binaryDocument.bin", "wb");
if (!fp) {
printf("\nCould not save the information to a binary file\n");
return;
}
fwrite(&size, sizeof(int), 1, fp);
fwrite(&eSize, sizeof(int), 1, fp);
for(unsigned i = 0; i < eSize; i++) {
fwrite(a[i], sizeof(**a), 1, fp);
}
fclose(fp);
}
int main() {
AUTOMOBILE *a[] = {
&(AUTOMOBILE) { "Ford", "Model T", 1908, 1000 },
&(AUTOMOBILE) { "Honda", "Accord", 2022, 20000 }
};
saveData(a, sizeof(a) / sizeof(*a), 42);
}
What you call size is usually referred to as max_size or capacity. eSize vs size is confusing. In either case, size is an artifact of your in memory representation so you don't need to persist that.
Prefer unsigned types when the value cannot be negative.
Types (AUTOMOBILE) are not by convention upper case (which is used for constants like enums and defined symbols).

C program for dijiktras shortest path not working [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How Can I debug a C program on Linux?
(4 answers)
Closed 1 year ago.
I have to build a program which takes in the vertices and edges from a csv file and uses an adjacency matrix to store the distance from one vertex to another and calls the function shortest_path which uses the dijkstra's algorithm to find the shortest path and calls the printpath function to print the information of all the vertices it goes through to get from the origin to the end.The information about the vertices is stored in the array of structures arr[].
The problem is that the program stops working when main() call the shortest_path() and the return value is 3221225725
The shortest_path function runs on its own in another program I made but is not called in the main when I execute this program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUFFER 100
#define MAX_NB 8000
#define INFINITY 9999
typedef struct edges edges;
struct edges{
int from,to,weight;
};
typedef struct stops stops;
struct stops {
int id;
float lat,lont;
char title[MAX_BUFFER];
};
stops* arr[MAX_NB]={0};
typedef struct Graph{
int vertices;
// int visited;
} Graph;
int visited[MAX_NB];
int amatrix[MAX_NB][MAX_NB];
int n;
Graph* create_graph(int num_nodes){
Graph* g = (Graph *)malloc(sizeof(struct Graph));
g->vertices=num_nodes;
int i,j;
for(i=0;i<num_nodes;i++){
for(j=0;j<num_nodes;j++){
amatrix[i][j]=0;
}
}
n=num_nodes;
return g;
}
Graph *graph;
int next_field( FILE *f, char *buf, int max ) {
int i=0, end=0, quoted=0;
for(;;) {
// fetch the next character from file
buf[i] = fgetc(f);
// if we encounter quotes then flip our state and immediately fetch next char
if(buf[i]=='"') { quoted=!quoted; buf[i] = fgetc(f); }
// end of field on comma if we're not inside quotes
if(buf[i]==',' && !quoted) { break; }
// end record on newline or end of file
if(feof(f) || buf[i]=='\n') { end=1; break; }
// truncate fields that would overflow the buffer
if( i<max-1 ) { ++i; }
}
buf[i] = 0; // null terminate the string
return end; // flag stating whether or not this is end of the line
}
void fetch_stops ( FILE *csv, struct stops *p) {
char buf[MAX_BUFFER];
next_field( csv, buf, MAX_BUFFER );
p->id = atoi(buf);
next_field( csv, p->title, MAX_BUFFER );
next_field( csv, buf, MAX_BUFFER );
p->lat = atof(buf);
next_field( csv, buf, MAX_BUFFER );
p->lont = atof(buf);
}
void fetch_edges ( FILE *csv, struct edges *p) {
char buf[MAX_BUFFER];
next_field( csv, buf, MAX_BUFFER );
p->from = atoi(buf);
next_field( csv, buf, MAX_BUFFER );
p->to = atoi(buf);
next_field( csv, buf, MAX_BUFFER );
p->weight = atoi(buf);
}
void print_stops( struct stops *p ) {
printf("%d \t \t %s \t %f %f\n",
p->id,p->title, p->lat, p->lont);
}/*
void print_edges( struct edges *p ) {
printf("%d \t \t %d \t %d\n",
p->from,p->to, p->weight);
}
*/
int load_vertices(char *fname){
FILE *f;
struct stops pArray[MAX_NB];
struct stops p;
f=fopen(fname,"r");
if(!f) {
printf("unable to open file\n");
return 0;
}
fetch_stops( f, &p ); // discard the header data in the first line
int ngames = 0;
while(!feof(f)) {
fetch_stops( f, &pArray[ngames]);
arr[ngames]=&pArray[ngames];
ngames++;
}
printf("loaded %d vertices\n",ngames);
fclose(f);
graph = create_graph(ngames);
return 1;
}
void add_edge(int from, int to, int weight){
amatrix[from][to]=weight;
amatrix[to][from]=weight;
}
int load_edges(char *fname/*,Graph *g*/){
FILE *f;
struct edges pArray[MAX_NB];
struct edges p;
f=fopen(fname,"r");
if(!f) {
printf("unable to open file\n");
return 0;
}
fetch_edges( f, &p ); // discard the header data in the first line
int nedges = 0;
int from,to,weight;
while(!feof(f)) {
fetch_edges( f, &pArray[nedges]);
nedges++;
}
int i;
for(i=0;i<nedges;i++){
add_edge(pArray[i].from,pArray[i].to,pArray[i].weight);
}
printf("loaded %d edges\n",nedges);
fclose(f);
return 1;
}
void printpath(int parent[], int u){
// Base Case : If j is source
if (parent[u] == - 1)
return;
printpath(parent, parent[u]);
printf("%d %s\n", arr[u]->id, arr[u]->title);
}
void shortest_path(int origin, int end){
printf("Works1");
int distance[MAX_NB];
int pred[MAX_NB];
int cost[MAX_NB][MAX_NB];
int count,minD,nextn,i,j;
pred[0]=-1;
int n=MAX_NB;
printf("Works2");
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
if (amatrix[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = amatrix[i][j];
}
}
for (i = 0; i <n; i++) {
distance[i] = cost[origin][i];
}
printf("Works1");
distance[origin] = 0;
printf("Works2");
visited[origin] = 1;
count = 1;
while (count < n - 1) {
minD = INFINITY;
for (i = 0; i < n; i++){
if ((distance[i] < minD) && (visited[i])!=1) {
minD = distance[i];
nextn = i;
}}
visited[nextn] = 1;
for (i = 0; i < n; i++)
if (!(visited[i]))
if (minD + cost[nextn][i] < distance[i]) {
distance[i] = minD + cost[nextn][i];
pred[i]=nextn;
}
count++;
}
printf("Works");
printpath(pred,end);
}
int main () {
load_vertices("vertices.csv");
load_edges("edges.csv")
printf("%d",amatrix[300][7490]);
shortest_path(300,253);
return EXIT_SUCCESS;
}

XTC file reading error

#include "xdrfile/xdrfile_xtc.h"
#include "xdrfile/xdrfile.h"
#include<stdio.h>
int main()
{
int nat;
int step;
float time;
float prec;
int status;
matrix box;
rvec k[3];
XDRFILE* xfp=xdrfile_open("test2.xtc","r");
status=read_xtc(xfp,nat,&step,&time,box,k,&prec);
xdrfile_close(xfp);
return 0;
}
I tried to run the code using the xtc library to read a trajectory frame of GROMACS... I am getting an error,
Segmentation error
Can you please help???
Looking at this code
Second parameter nat must be set to a value retrieved read_xtc_natoms function. The value must be initialized anyway.
Moreover the array k width must match the nat value.
#include "xdrfile/xdrfile_xtc.h"
#include "xdrfile/xdrfile.h"
#include<stdio.h>
int main(void)
{
int nat;
int step;
float time;
float prec;
int status;
matrix box;
int status;
char fileName[] = "test2.xtc";
status = read_xtc_natoms(fileName, &nat);
if (status != exdrOK)
{
XDRFILE* xfp = xdrfile_open(fileName, "r");
if (xfp != NULL)
{
rvec k[nat];
status = read_xtc(xfp, nat, &step, &time, box, k, &prec);
xdrfile_close(xfp);
}
else
{
perror("File not opened:");
}
}
else
{
fprintf(stderr, "read_xtc_natoms failure; return code %d", status);
}
return 0;
}
In the above code I used VLAs to create the k array, but you can use dynamic memory too:
#include "xdrfile/xdrfile_xtc.h"
#include "xdrfile/xdrfile.h"
#include<stdio.h>
int main(void)
{
int nat;
int step;
float time;
float prec;
int status;
matrix box;
int status;
char fileName[] = "test2.xtc";
status = read_xtc_natoms(fileName, &nat);
if (status != exdrOK)
{
rvec *k = malloc(nat * sizeof(rvec));
if (k != NULL)
{
XDRFILE* xfp = xdrfile_open(fileName, "r");
if (xfp != NULL)
{
status = read_xtc(xfp, nat, &step, &time, box, k, &prec);
xdrfile_close(xfp);
}
else
{
perror("File not opened:");
}
free(k);
}
else
{
fprintf(stderr, "Error in dynamic allocation of k vector\n");
}
}
else
{
fprintf(stderr, "read_xtc_natoms failure; return code %d", status);
}
return 0;
}

Segmentation fault happened in Linux but works in Mac

I have a c code which wrote in my Mac laptop in Xcode but it didn't work in Linux system.
I run this code by two ways:
1.One is run in Eclipse but the while loop didn't look like finish. Please find the message below:
Please wait while calculating...
But not more message in the console. It looks like while loop can't finish by some reason.
2.The second way is that I complier the code directly in Linux environment by the command:
cc -std=c99 main.c -o main
Then run by the command:
./main
The message shows that:
Please wait while calculating... Segmentation fault (core dumped)
I checked by gdb
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a9bd4a in ?? () from /lib/x86_64-linux-gnu/libc.so.6
My data is saved in:
/home/alan_yu/workspace/scandi.csv
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char **split(char *line, char sep, int fields) {
char **r = (char **)malloc(fields * sizeof(char*));
int lptr = 0, fptr = 0;
r[fptr++] = line;
while (line[lptr]) {
if (line[lptr] == sep) {
line[lptr] = '\0';
r[fptr] = &(line[lptr+1]);
fptr++;
}
lptr++;
}
return r;
}
int cmpfunc (const void * a, const void * b)
{
return *(double *)a > *(double *)b ? 1 : -1;
}
#define LINE_SIZE 1000000
#define EXPECTED_STOCK_SIZE 10000000
void calculate2(char * fileName) {
printf("Please wait while calculating...\n");
// Open the file for reading.
FILE *file = fopen(fileName, "r");
// maximun size of the line to read.
// memory allocation for the line to read.
char* line = malloc(LINE_SIZE);
// char **stockNameArray = malloc( sizeof(char *) * EXPECTED_STOCK_SIZE);
// int stockNameArrayPos = 0;
double *bidArray = malloc( sizeof(double) * EXPECTED_STOCK_SIZE );
int bidArrayPos = 0;
double *askArray = malloc( sizeof(double) * EXPECTED_STOCK_SIZE);
int askArrayPos = 0;
double *spreadArray = malloc( sizeof(double) * EXPECTED_STOCK_SIZE);
int spreadArrayPos = 0;
double sum=0;
int i=0,j=0;
while (fgets(line, LINE_SIZE, file)!= NULL){
// printf("Please wait while ...%d\n ", j);
j++;
char **fields = split(line, ',', 15);
const char * volvbEquity = "VOLVB SS Equity";
int comp = strcmp(fields[0], volvbEquity);
if (comp == 0) {
double bidValue = atof(fields[2]);
double askValue = atof(fields[3]);
bidArray[bidArrayPos++] = bidValue;
askArray[askArrayPos++] = askValue;
if (askValue - bidValue > 0) {
double spreadValue = ((askValue - bidValue) / (askValue + bidValue) * 20000);
spreadArray[spreadArrayPos++] = spreadValue;
sum = sum + spreadValue;
}
}
}
//quick sort the spread
qsort(spreadArray, spreadArrayPos, sizeof(double), cmpfunc);
int mediumPos;
double mean;
double medium;
if(spreadArrayPos % 2 == 0) {
mediumPos = spreadArrayPos / 2;
medium = (spreadArray[mediumPos] + spreadArray[mediumPos+1]) / 2;
} else {
mediumPos = (spreadArrayPos)/2 + 1;
medium = spreadArray[mediumPos];
}
mean = sum / spreadArrayPos;
printf("Please find mean and medium %f %f\n", mean, medium);
free(bidArray);
free(askArray);
free(spreadArray);
}
int main(int argc, char **argv) {
calculate2("/home/alan_yu/workspace/scandi.csv");
return(0);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void split(char *line, char sep, char **fields) {
int lptr = 0, fptr = 0;
fields[fptr++] = line;
while (line[lptr]) {
if (line[lptr] == sep) {
line[lptr] = '\0';
fields[fptr] = &(line[lptr+1]);
fptr++;
}
lptr++;
}
}
int cmpfunc (const void * a, const void * b) {
return *(double *)a > *(double *)b ? 1 : -1;
}
#define LINE_SIZE 1000000
#define EXPECTED_STOCK_SIZE 10000000
#define COLUMN_NUM 15
void calculate2(char * fileName) {
printf("Please wait while calculating...\n");
// Open the file for reading.
FILE *file = fopen(fileName, "r");
// maximun size of the line to read.
// memory allocation for the line to read.
char* line = malloc(LINE_SIZE);
// char **stockNameArray = malloc( sizeof(char *) * EXPECTED_STOCK_SIZE);
// int stockNameArrayPos = 0;
double *bidArray = malloc( sizeof(double) * EXPECTED_STOCK_SIZE );
int bidArrayPos = 0;
double *askArray = malloc( sizeof(double) * EXPECTED_STOCK_SIZE);
int askArrayPos = 0;
double *spreadArray = malloc( sizeof(double) * EXPECTED_STOCK_SIZE);
int spreadArrayPos = 0;
double sum=0;
int i=0,j=0;
while (fgets(line, LINE_SIZE, file)!= NULL){
// printf("Please wait while ...%d\n ", j);
j++;
char **fields = malloc(sizeof(char *) * COLUMN_NUM);
split(line, ',', fields);
const char * volvbEquity = "VOLVB SS Equity";
int comp = strcmp(fields[0], volvbEquity);
if (comp == 0) {
double bidValue = atof(fields[2]);
double askValue = atof(fields[3]);
bidArray[bidArrayPos++] = bidValue;
askArray[askArrayPos++] = askValue;
if (askValue - bidValue > 0) {
double spreadValue = ((askValue - bidValue) / (askValue + bidValue) * 20000);
spreadArray[spreadArrayPos++] = spreadValue;
sum = sum + spreadValue;
}
}
// free memory for fields.
free(fields);
}
// free memory for the line variable.
free(line);
//quick sort the spread
qsort(spreadArray, spreadArrayPos, sizeof(double), cmpfunc);
int mediumPos;
double mean;
double medium;
if(spreadArrayPos % 2 == 0) {
mediumPos = spreadArrayPos / 2;
medium = (spreadArray[mediumPos] + spreadArray[mediumPos+1]) / 2;
} else {
mediumPos = (spreadArrayPos)/2 + 1;
medium = spreadArray[mediumPos];
}
mean = sum / spreadArrayPos;
printf("Please find mean and medium %f %f\n", mean, medium);
free(bidArray);
free(askArray);
free(spreadArray);
}
int main(int argc, char **argv) {
calculate2("/home/alan_yu/workspace/scandi.csv");
return(0);
}
On Linux, always run the program in valgrind if it is crashing.
It will not only tell you exactly what is wrong in your code, but also specify what code lines are responsible for the error.
You need to check the return value of fopen! I would suggest doing the same thing for malloc, but it's much less likely that malloc is failing due to a missing file or typographical error particularly if you're allocating large chunks! You wouldn't want to dereference a null pointer, right?
I'm assuming each line has at least four comma-separated fields, because you're using fields[3]. You should probably work out how to guard against using uninitialised values here. I'd start by re-engineering split so that you have some terminal NULL value or something in its output (and while we're on that topic, don't forget to free the return value).
Is it possible that you might be dividing by zero? That'd be something else you need to guard against.
Shouldn't cmpfunc return 0 when items are equal? I've seen implementations crash when return values for comparison functions for qsort and bsearch are inconsistent.
You claimed below in a comment that your lines have fifteen commas. This implies that you have sixteen fields (count them below), since the number of fields is n+1 where n is the number of separators.
field1, field2, field3, field4,
field4, field6, field7, field8,
field9, field10,field11,field12,
field13,field14,field15,field16
There are fifteen commas and sixteen fields in this table. You're only allocating enough for fifteen fields, however. This is a buffer overflow, more typical undefined behaviour.
Finally, I find out the problem comes from the
while (fgets(line, LINE_SIZE, file)!= NULL){
char **fields = split(line, ',', 15);
I have changed it to
char **fields = malloc(sizeof(char *) * 15 * 10000);
while (fgets(line, LINE_SIZE, file)!= NULL){
I haven't try to allocate a large memory to **fields after the while loop due to it takes too much memory to my machine.
It looks like under gcc compile that if I do:
while (fgets(line, LINE_SIZE, file)!= NULL){
char **fields = split(line, ',', 15);
It won't overwrite the **fields from last time. But it works in Mac
Not sure is that correct?
In the end, thanks for all of you guys help for my problem.

Program running in debug mode in C::B only

I am currently writing a program which at some point needs to store the sizes of all the files in a specific folder in an array. My program crashes when running it on Code::Blocks in release mode, but does run in debug mode. It also runs without any problems on XCode on Mac OS. Here's the code:
#define MALLOC_ERROR -1
#define DIR_ACCESS_ERROR -2
#define FILE_ACCESS_ERROR -3
#define FILE_OPEN_ERROR -4
#define OUTPUT_FILE_OPEN_ERROR -5
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <math.h>
int compare(const void*, const void*);
int getFileSizeMarginNumbers(char[], int, unsigned long int*);
int main(void){
FILE *out;
int n;
int i, count = 1;
unsigned long int *fileSizeMarginNumber;
char directoryName[] = "C:\\Users\\Борис\\Desktop\\new\\";
char outputFilePath[] = "C:\\Users\\Борис\\Desktop\\out.txt";
printf("Enter number of files in directory:");
scanf("%d", &n);
if (!(fileSizeMarginNumber = (unsigned long int*)malloc(n*sizeof(unsigned long int)))){
printf("Not enough memory");
return MALLOC_ERROR;
}
switch (getFileSizeMarginNumbers(directoryName, n, fileSizeMarginNumber)) {
case MALLOC_ERROR:
return MALLOC_ERROR;
break;
case DIR_ACCESS_ERROR:
return DIR_ACCESS_ERROR;
break;
case FILE_ACCESS_ERROR:
return FILE_ACCESS_ERROR;
break;
case FILE_OPEN_ERROR:
return FILE_OPEN_ERROR;
break;
}
qsort(fileSizeMarginNumber, n, sizeof(unsigned long int), compare);
if (!(out = fopen(outputFilePath, "w"))){
printf("Unable to open output file");
return OUTPUT_FILE_OPEN_ERROR;
}
for (i=1; i<n; ++i) {
if (fileSizeMarginNumber[i] == fileSizeMarginNumber[i - 1])
++count;
else{
fprintf(out, "%ldKB - %ldKB: %d file(s);\n", (fileSizeMarginNumber[i - 1] - 1)*16, fileSizeMarginNumber[i - 1]*16, count);
count = 1;
}
}
fprintf(out, "%ldKB - %ldKB: %d files;\n", (fileSizeMarginNumber[i - 1] - 1)*16, fileSizeMarginNumber[i - 1]*16, count);
return 0;
}
int getFileSizeMarginNumbers(char directoryName[], int n, unsigned long int *fileSizeMarginNumber){
int i, fileDescriptor;
struct dirent *file;
struct stat currentSize;
DIR *directory;
FILE *buf;
if (!(directory = opendir(directoryName))) {
printf("Unable to get access to the specified directory");
return DIR_ACCESS_ERROR;
}
for (i=0;i<2;++i){
if (!(file = readdir(directory))) {
printf("Unable to get access to a file in the specified directory");
return FILE_ACCESS_ERROR;
}
}
for (i=0; i<n; ++i) {
if (!(file = readdir(directory))) {
printf("Unable to get access to a file in the specified directory");
return FILE_ACCESS_ERROR;
}
printf("%s", strcat(strdup(directoryName), file->d_name));
if (!(buf = fopen(strcat(strdup(directoryName), file->d_name), "r"))){
printf("Unable to process a file in the specified directory");
return FILE_OPEN_ERROR;
}
fileDescriptor = fileno(buf);
fstat(fileDescriptor, &currentSize);
fileSizeMarginNumber[i] = (unsigned long int)truncl(currentSize.st_size/(1024*16)) + 1;
fclose(buf);
}
return 0;
}
int compare(const void *a, const void *b){
if ((*(long int*)a - *(long int*)b) < 0)
return -1;
else if ((*(long int*)a - *(long int*)b) == 0)
return 0;
else
return 1;
}
The problem seems to be located in the following block:
for (i=0; i<n; ++i) {
if (!(file = readdir(directory))) {
printf("Unable to get access to a file in the specified directory");
return FILE_ACCESS_ERROR;
}
printf("%s", strcat(strdup(directoryName), file->d_name));
if (!(buf = fopen(strcat(strdup(directoryName), file->d_name), "r"))){
printf("Unable to process a file in the specified directory");
return FILE_OPEN_ERROR;
}
fileDescriptor = fileno(buf);
fstat(fileDescriptor, &currentSize);
fileSizeMarginNumber[i] = (unsigned long int)truncl(currentSize.st_size/(1024*16)) + 1;
fclose(buf);
}
The program is supposed to open all files in a folder step-by-step. However, the second or third call to fopen sometimes triggers the following exception:
Program received signal SIGSEGV, Segmentation fault.
In ntdll!RtlLargeIntegerToChar () (C:\Windows\system32\ntdll.dll)
I do not understand this dependency on where I am running my program and I would've been very grateful for your help.
Thank you very much in advance.
That strcat() in fopen() is not correct:
strcat(strdup(directoryName), file->d_name)
First strdup() allocates strlen(directoryName)+1 bytes and copies directoryName then strcat() wants to append file->d_name to that copy. But as there is no extra space allocated a seg fault might occur. Do something like that instead:
char *pathname = MALLOC( strlen(directoryName) + strlen(file->d_name) + 1 );
strcpy( pathname, directoryName );
strcat( pathname, file->d_name );
And don't forget to free(pathname) when you don't need it any more

Resources