Why does this code not work in Linux if it shows an error message - c

I have to make the labyrinth program, which works in Windows under Code Blocks; but when I want to run it in Linux it doesn't work.
When I start debugging, it works correctly until line 63 returns and crashes.
Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
Quit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max_col 50
#define max_row 50
#define max_numOflabyrinth 50
#define max_checkPt 50
#define MAX_LINES 10
#define MAX_LINE_LENGTH 2506
enum{UP, DOWN, LEFT, RIGHT};
typedef struct POSITION{
int x;
int y;
} POSITION;
typedef struct PFAD{
POSITION* pos;
int step;
} PFAD;
typedef struct CHECKPOINT{
int seqNum;
int total_span;
int next_span;
int stepNum;
POSITION pos;
POSITION next_steps[3];
//CHECKPOINT* previous_checkPt; //C don't support this.
} CHECKPOINT;
typedef struct LIS_CHECKPOINT{
CHECKPOINT checkPt;
CHECKPOINT* prev_checkPt;
} LIS_CHECKPOINT;
typedef struct LABYRINTH{
char name[10];
char** landkarte; //2D-array landkarte[y][x] y=row x=col
int max_x;
int max_y;
int max_step; //max. laufzeit für while()
POSITION start;
POSITION end;
} LABYRINTH;
int pos_cmp(POSITION a, POSITION b){
if(a.x == b.x && a.y == b.y){return 1;}
else{return 0;}
}
void pos_set(POSITION* des, const POSITION src){
des->x = src.x;
des->y = src.y;
}
void init_LABYRINTH(LABYRINTH* laby){
laby->landkarte=NULL;
laby->max_x=0;
laby->max_y=0;
laby->max_step=0;
laby->start.x=0;
laby->start.y=0;
laby->end.x=0;
laby->end.y=0;
}
/*
int erkunden(LABYRINTH* labyrinth){
POSITION cur_pos;
pos_set(&cur_pos, labyrinth->start);
POSITION check_steps[3]; //only three directions
PFAD footprt;
footprt.pos = calloc(labyrinth->max_x*labyrinth->max_y, sizeof(POSITION));
footprt.step = 0;
CHECKPOINT* prt_last_
}
*/
int erkunden(LABYRINTH* labyrinth){
fflush(stdin);
POSITION cur_pos;
//initialisieren
pos_set(&cur_pos, labyrinth->start);
POSITION check_steps[3]; //max. möglich 3 Richtung
PFAD footprt;
footprt.pos = calloc(labyrinth->max_x*labyrinth->max_y, sizeof(POSITION));
footprt.step = 0;
CHECKPOINT* ptr_last_checkPt;
LIS_CHECKPOINT* lis_checkPt;
lis_checkPt = calloc(max_checkPt, sizeof(LIS_CHECKPOINT));
int total_checkPt=0;
int i, j;
int if_break=1;
int numOFsteps=0;
int loopcontroll=0;
char** map= calloc(labyrinth->max_y, sizeof(char*));
for(i=0;i<labyrinth->max_y;i++){
map[i]=calloc(labyrinth->max_x, sizeof(char));
}
while(!pos_cmp(cur_pos, labyrinth->end) && if_break){
map[cur_pos.y][cur_pos.x]=1;
pos_set(&footprt.pos[footprt.step], cur_pos);
//oben
if(cur_pos.y-1>=0 && labyrinth->landkarte[cur_pos.y-1][cur_pos.x]!='w' && map[cur_pos.y-1][cur_pos.x]!=1){
check_steps[numOFsteps].x=cur_pos.x;
check_steps[numOFsteps].y=cur_pos.y-1;
numOFsteps++;
}
//unten
if(cur_pos.y+1<labyrinth->max_y && labyrinth->landkarte[cur_pos.y+1][cur_pos.x]!='w' && map[cur_pos.y+1][cur_pos.x]!=1){
check_steps[numOFsteps].x=cur_pos.x;
check_steps[numOFsteps].y=cur_pos.y+1;
numOFsteps++;
}
//links
if(cur_pos.x-1>=0 && labyrinth->landkarte[cur_pos.y][cur_pos.x-1]!='w' && map[cur_pos.y][cur_pos.x-1]!=1){
check_steps[numOFsteps].x=cur_pos.x-1;
check_steps[numOFsteps].y=cur_pos.y;
numOFsteps++;
}
//rechts
if(cur_pos.x+1<labyrinth->max_x && labyrinth->landkarte[cur_pos.y][cur_pos.x+1]!='w' && map[cur_pos.y][cur_pos.x+1]!=1){
check_steps[numOFsteps].x=cur_pos.x+1;
check_steps[numOFsteps].y=cur_pos.y;
numOFsteps++;
}
if(numOFsteps==0){
do{
ptr_last_checkPt=lis_checkPt[ptr_last_checkPt->seqNum].prev_checkPt;
j=(++ptr_last_checkPt->next_span);
}
while(ptr_last_checkPt->next_span > ptr_last_checkPt->total_span-1);
pos_set(&cur_pos, ptr_last_checkPt->next_steps[j]);
footprt.step=ptr_last_checkPt->stepNum;
}
else if(numOFsteps==1){
pos_set(&cur_pos, check_steps[0]);
}
else {
ptr_last_checkPt = &lis_checkPt[total_checkPt].checkPt;
ptr_last_checkPt->seqNum=total_checkPt;
if(total_checkPt==0){
lis_checkPt[total_checkPt].prev_checkPt=NULL;}
else{
lis_checkPt[total_checkPt].prev_checkPt=&lis_checkPt[total_checkPt-1].checkPt;
}
for(i=0;i<numOFsteps;i++){
pos_set(&ptr_last_checkPt->next_steps[i], check_steps[i]);
}
pos_set(&ptr_last_checkPt->pos, cur_pos);
ptr_last_checkPt->total_span=numOFsteps;
ptr_last_checkPt->next_span=0;
ptr_last_checkPt->stepNum=footprt.step;
pos_set(&cur_pos, ptr_last_checkPt->next_steps[0]);
total_checkPt++;
}
numOFsteps=0;
footprt.step++;
loopcontroll++;
if(loopcontroll>labyrinth->max_step) if_break=0;
}//end loop
//save the solution in the labyrith
for(i=0;i<footprt.step;i++){
labyrinth->landkarte[footprt.pos[i].y][footprt.pos[i].x]='*';
}
//free
free(footprt.pos);
free(lis_checkPt);
for(i=0;i<labyrinth->max_y;i++) free(map[i]);
free(map);
//rückgabewert
if(loopcontroll>labyrinth->max_step) return 1;
else return 0;
}
FILE* open_labyrinth_file(char* file_name){
FILE* file_landkarte = fopen(file_name, "r");
if (file_landkarte==NULL){
printf("Fehler bei Einlesen der Text-Datei\n");
return NULL;
}
printf("\"%s\" eingelesen!\n",file_name);
return file_landkarte;
}
LABYRINTH* load_labyrinth(const char* map_line, int max_x_size, int max_y_size){
LABYRINTH* labyrinth=NULL;
init_LABYRINTH(labyrinth);
int map_size = strlen(map_line)-1; //
int i=0,j=0,k=0; //variables to help
labyrinth->max_step=0;
int b=0, z=0;
//name for the Labyrinth
for(i=0;i<6;i++){
if(map_line[i] == '='){
labyrinth->name[i] = '\0';
break;
}else{
labyrinth->name[i] = map_line[i];
}
}
k = strlen(labyrinth->name)+1;
map_size -= k;
for(i=k; i<max_x_size; i++){
//if the labyrinth is not quadratic i.e. has an exact root
if(i*i == map_size){
labyrinth->max_x=i;
labyrinth->max_y=i;
break;
}
if(i*i>map_size){
printf("Dimensions incorrect: map not quaratic!: %s \n", labyrinth->name);
return NULL;
}
}
//loop to check that the maze contains one exit and one entrance
for(i=k;i<map_size;i++){
if(map_line[i]=='b'){b=1;}
if(map_line[i]=='z'){z=1;}
}
if(b!=1||z!=1){
printf("The map not contains an start and an end: %s \n", labyrinth->name);
return NULL;
}else{
printf("The map contains an start and an end: %s \n", labyrinth->name);
}
labyrinth->landkarte = calloc(labyrinth->max_y, sizeof(char*));
for(i=0;i<labyrinth->max_y;i++){
labyrinth->landkarte[i] = calloc(labyrinth->max_x, sizeof(char*));
}
for(i=0;i<labyrinth->max_y;i++){
for(j=0;j<labyrinth->max_x;j++){
labyrinth->landkarte[i][j]=map_line[i*labyrinth->max_x+j+k];
if(labyrinth->landkarte[i][j]=='b'){
labyrinth->start.x=j;
labyrinth->start.y=i;
}
if(labyrinth->landkarte[i][j]=='z'){
labyrinth->end.x=j;
labyrinth->end.y=i;
}
if(labyrinth->landkarte[i][j]=='k'){
labyrinth->max_step+=2;
}
}
}
return labyrinth;
}
/*
LABYRINTH* load_labyrinth(const char* landkarte_zeile, int max_x_size, int max_y_size){
int landkarte_size=strlen(landkarte_zeile);
int i,j,k;
LABYRINTH* labyrinth;
init_LABYRINTH(labyrinth);
labyrinth->max_step=0;
if(max_x_size!=max_y_size){
printf("Dimensionsangaben fehlerhaft: max_x und max_y muss identisch sein!/n");
return NULL;
}
for(i=0;i<5;i++){
if(landkarte_zeile[i]=='='){
labyrinth->name[i]='\0';
break;
}
labyrinth->name[i] = landkarte_zeile[i];
}
k=strlen(labyrinth->name)+1;
landkarte_size-=k;
for(i=3;i<=max_x_size;i++){
if(i*i==landkarte_size){
labyrinth->max_x=i;
labyrinth->max_y=i;
break;
}
if(i*i>landkarte_size){
printf("Dimensionen fehlerhaft: Landkarte nicht quaratisch!: %s \n",labyrinth->name);
return NULL;
}
}
labyrinth->landkarte = calloc(labyrinth->max_y, sizeof(char*));
for(i=0;i<labyrinth->max_y;i++){
labyrinth->landkarte[i] = calloc(labyrinth->max_x, sizeof(char*));
}
for(i=0;i<labyrinth->max_y;i++){
for(j=0;j<labyrinth->max_x;j++){
labyrinth->landkarte[i][j]=landkarte_zeile[i*labyrinth->max_x+j+k];
if(labyrinth->landkarte[i][j]=='b'){
labyrinth->start.x=j;
labyrinth->start.y=i;
}
if(labyrinth->landkarte[i][j]=='z'){
labyrinth->end.x=j;
labyrinth->end.y=i;
}
if(labyrinth->landkarte[i][j]=='k'){
labyrinth->max_step+=2;
}
}
}
return labyrinth;
}
*/
/*
//old
char* print_labyrinth(LABYRINTH* labyrinth){
if(labyrinth==NULL){
printf("Plot-Fehler: kein Labyrith gefunden.\n");
return;
}
char buffer[100];
char character = 'c';
int i,j;
printf("Labyrinth: %s\n", labyrinth->name);
//strcat(buffer, labyrinth->name);
for(i=0;i<labyrinth->max_y;i++){
for(j=0;j<labyrinth->max_x;j++){
if(labyrinth->landkarte[i][j]=='w'){
character = '#';
printf(character);
strncat(buffer, &character, 1);
}
else if(labyrinth->landkarte[i][j]=='k'){
printf(" ");
//strcat(buffer, ' ');
}
else{
printf("%c", labyrinth->landkarte[i][j]);
//strcat(buffer, labyrinth->landkarte[i][j]);
}
}
printf("\n");
//strcat(buffer,"\n");
}
printf("Start: (%i,%i) ", labyrinth->start.x,labyrinth->start.y);
printf("End: (%i,%i)\n", labyrinth->end.x,labyrinth->end.y);
return buffer;
} */
//new
char* print_labyrinth(LABYRINTH* labyrinth) {
if (labyrinth == NULL) {
return strdup("Plot-Fehler: kein Labyrinth gefunden.\n");
}
char* buffer = malloc(sizeof(char) * 10000);
if (buffer == NULL) {
// handle error
}
int offset = 0;
offset += sprintf(buffer + offset, "Labyrinth: %s\n", labyrinth->name);
for (int i = 0; i < labyrinth->max_y; i++) {
for (int j = 0; j < labyrinth->max_x; j++) {
if (labyrinth->landkarte[i][j] == 'w') {
offset += sprintf(buffer + offset, "#");
} else if (labyrinth->landkarte[i][j] == 'k') {
offset += sprintf(buffer + offset, " ");
} else {
offset += sprintf(buffer + offset, "%c", labyrinth->landkarte[i][j]);
}
}
offset += sprintf(buffer + offset, "\n");
}
offset += sprintf(buffer + offset, "Start: (%i,%i) End: (%i,%i)\n",
labyrinth->start.x, labyrinth->start.y, labyrinth->end.x, labyrinth->end.y);
printf("%s", buffer);
return buffer;
}
void save_to_file(char* text, char* filename) {
FILE* file = fopen(filename, "wt");
if (file == NULL) {
printf("Error opening file.\n");
return;
}
fprintf(file, "%s", text);
fclose(file);
printf("Text saved to file %s\n", filename);
}
int main()
{
/*
int i,j,k;
int *ergibnis;
int total_labyr=0;
char charbuff[2506]={'\0'};
char* solution = malloc(sizeof(char) * 10000);
int offset = 0;
LABYRINTH** labyrinth[max_numOflabyrinth];
FILE* file_landkarte = open_labyrinth_file("labyrinth_karte.txt");
if(fgets(charbuff,2506,file_landkarte)!=EOF){
labyrinth[total_labyr]=load_labyrinth(charbuff, 50, 50);
total_labyr++;
}
ergibnis = calloc(total_labyr, sizeof(int));
for(i=0;i<total_labyr;i++){
if(!erkunden(labyrinth[i])){ // ! weil erkunden liefert 0 wenn erfolgreich ist
ergibnis[i] = 1;
offset += sprintf(solution + offset, print_labyrinth(labyrinth[j]));
}
}
print_labyrinth(labyrinth);
save_to_file(solution, "solvelab.txt");
*/
LABYRINTH* labyrinth[MAX_LINES];
init_LABYRINTH(&labyrinth);
int i=0, j=0;
char charbuff[2506];
char* solution;
solution =(char*)malloc(sizeof(char) * 2506);
int offset = 0;
FILE* file_landkarte = open_labyrinth_file("labyrinth_karte.txt");
/* for(j=0; j< MAX_LINES; j++){
fflush(stdin);
init_LABYRINTH(labyrinth[j]);
}
*/
while (fgets(charbuff, MAX_LINE_LENGTH, file_landkarte) != NULL) {
labyrinth[i] = load_labyrinth(charbuff, max_row, max_col);
if(labyrinth[i]!=NULL){
print_labyrinth(labyrinth[i]);
if(!erkunden(labyrinth[i])){ // ! weil erkunden liefert 0 wenn erfolgreich ist
//solution = print_labyrinth(labyrinth[j]);
//strcpy(,print_labyrinth(labyrinth[j]));
offset += sprintf(solution + offset, print_labyrinth(labyrinth[i]));
printf("labyrinth solved!\n");
save_to_file(solution, "solvelab.txt");
}
else{
printf("labyrinth has no solution!\n");
}
}else{
printf("no posible: %i \n",j);
}
i++;
}
/*
for (j = 0; j < 6 ;j ++){
// labyrinth = load_labyrinth(lines[j],max_row, max_col);
if(labyrinth[j]!=NULL){
print_labyrinth(labyrinth[j]);
if(!erkunden(labyrinth[j])){ // ! weil erkunden liefert 0 wenn erfolgreich ist
//solution = print_labyrinth(labyrinth[j]);
//strcpy(,print_labyrinth(labyrinth[j]));
offset += sprintf(solution + offset, print_labyrinth(labyrinth[j]));
printf("labyrinth solved!\n");
//save_to_file(solution, "solvelab.txt");
}
else{
printf("labyrinth has no solution!\n");
}
}else{
printf("no posible\n: %i ",j);
}
}
*/
//save_to_file(solution, "solvelab.txt");
fclose(file_landkarte);
return 0;
}
labyrinth_karte.txt
L3=wwwwwwwskkkwwwkwswwskwwwwwkkzwwwwwww
L4=wwwwbwwskkkwwwkwswwskwwwwwkkswwwwwww
L5=wwwbwwwskkkwwwwwswwskwwwwwkkzwwwwwww
L6=wwwbwwkskkkwwwkwswwskwwwwwkkzwwwwwww
L1=wwwbwwwskkkwwwkwswwskwwwwwkkzwwwwwww
L2=wwwwwwwwwswkkkswwkwkwzwwwkkkwwswbkwwswkwwkkkkwkwwswwkkkwwwwwwwww

Related

Why is does the file become NULL?

I'm new on the subject of data structures so forgive me if Im asking a stupid question, I've been trying to figure this out myself but got nowhere.
These are the functions I'm working on and I think I initialized the file properly. However I couldn't understand why the function GetString prints an infinite loop of spaces. I have another function that exported some data on the said file. When i deleted the ImportListOfCompanyData function everything seems in order and the file is exported as it should be. However when ImportListOfCompanyData is there, the file is NULL.
void char * GetString(FILE *fp)
{
char c;
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
void ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c;
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
GetString(fp);
fclose(fp);
}
Someone asked for the complete code: It's bit long sorry!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNUM 100
struct Department
{
char DepName[MAXNUM];
int NuEmp;
double Budget;
int dflag;
};
typedef struct Department DEP;
struct CompanyType
{
char CompName[MAXNUM];
char OwnerName[MAXNUM];
int Year;
double StockPrice;
int flag;
DEP Dep[MAXNUM];
};
struct ImpDepartment
{
char IDepName[MAXNUM];
int INuEmp;
double IBudget;
int Idflag;
};
typedef struct ImpDepartment IDEP;
struct ImpCompanyType
{
char ICompName[MAXNUM];
char IOwnerName[MAXNUM];
int IYear;
double IStockPrice;
int Iflag;
IDEP IDep[MAXNUM];
};
void CreateCompany(struct CompanyType s[], char * cname, char * cowner, int year, double sprice, int i)
{
strcpy(s[i].CompName, cname);
strcpy(s[i].OwnerName, cowner);
s[i].Year = year;
s[i].StockPrice = sprice;
s[i].flag = 0;
}
int PrintCompany(struct CompanyType s[], int maxit1, int maxit2)
{
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
printf("%d. Company %s: \n\n", i + 1, s[i].CompName);
printf("****************\n");
printf("Owned by: %s\n", s[i].OwnerName);
printf("Establishment year: %d\n", s[i].Year);
printf("Stock price: %.2lf\n", s[i].StockPrice);
printf("****************\n\n");
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
printf("****************\n");
printf("%d. Department %s: \n", j + 1, s[i].Dep[j].DepName);
printf("Number of employees: %d\n", s[i].Dep[j].NuEmp);
printf("Budget: %.2lf\n", s[i].Dep[j].Budget);
printf("****************\n\n");
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
}
int CompareName(char * str1, char * str2)
{
char *stra, *strb;
int result;
result = strcmp(str2, str1);
return result;
}
void DeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
s[i].flag = 1;
printf("Company %s was successfully deleted!\n", s[i].CompName);
}
else
printf("The input is wrong!");
}
void UnDeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 0)
{
printf("The Company %s wasn't deleted in the first place.\n\n", s[i].CompName);
}
else
{
s[i].flag = 0;
printf("Company %s was successfully undeleted!\n\n", s[i].CompName);
}
}
else
printf("The input is wrong!");
}
int SearchForCompany(struct CompanyType s[], char * cname, int maxit, int a)
{
int i = 0;
int check = 0;
int m = 0;
while(i <= maxit)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 1)
{
printf("The company ""%s"" doesn't exist\n\n", cname);
}
else
{
if(a == 1)
{
printf("The company %s was found!", s[i].CompName, s[i].CompName);
m = 1;
}
else
m = 1;
}
}
else
printf("The company ""%s"" doesn't exist\n\n", cname);
if (m == 1)
return i;
else
return -1;
}
void AddDeparments(struct CompanyType s[], char * cname, int maxit, int a, char * dname, int nem, double bud, int depno)
{
int n;
n = SearchForCompany(s,cname, maxit, a);
if(maxit == -1)
return -1;
strcpy(s[n].Dep[depno].DepName, dname);
s[n].Dep[depno].NuEmp = nem;
s[n].Dep[depno].Budget = bud;
s[n].Dep[depno].dflag = 0;
printf("The department %s was created in the %s company\n",s[n].Dep[depno].DepName, s[n].CompName);
}
int SearchForDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
printf("The department ""%s"" doesn't exist.\n\n", dname);
}
else
(*succ) = 1;
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
int SearchForDelDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
(*succ) = 1;
}
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
void DeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
{
s[i].Dep[j].dflag = 1;
printf("The department %s was deleted from the %s company\n", dname, s[i].CompName);
}
}
void UnDeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDelDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
s[i].Dep[j].dflag = 0;
if(s[i].Dep[j].dflag == 0)
printf("The department %s was undeleted\n", dname);
}
ExportListOfCompanyData(struct CompanyType s[], int maxit1, int maxit2, char * FileName)
{
FILE *fp;
fp = fopen(FileName, "w");
if (fp==NULL)
{
printf("Error creating the file \n");
return -1;
}
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].CompName);
fprintf(fp,"%s\n", s[i].OwnerName);
fprintf(fp,"%d\n", s[i].Year);
fprintf(fp,"%.2lf\n\n", s[i].StockPrice);
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].Dep[j].DepName);
fprintf(fp,"%d\n", s[i].Dep[j].NuEmp);
fprintf(fp,"%.2lf\n\n", s[i].Dep[j].Budget);
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
fclose(fp);
}
char * GetString(FILE *fp)
{
char * str; char c;
str = (char *)malloc(sizeof(char)* MAXNUM);
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c, *str;
str = (char *)malloc(sizeof(char)* MAXNUM);
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
int i = 0, j = 0, n;
GetString(fp);
fclose(fp);
return 0;
}
int main()
{
struct CompanyType CompanyList[MAXNUM];
CreateCompany(CompanyList, "alara inc", "alara", 2020, 6969, 0);
CreateCompany(CompanyList, "Shah inc", "shah", 2020, 3245, 1);
DeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
UnDeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
SearchForCompany(CompanyList, "alara inc", 1, 1);
AddDeparments(CompanyList, "alara inc", 1, 0, "computer", 20, 300, 0);
AddDeparments(CompanyList, "Shah inc", 1, 0, "chemistry", 30, 450, 0);
DeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
UnDeleteDepartments(CompanyList, 0, 1, 0, "computer");
PrintCompany(CompanyList, 1, 1);
UnDeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
ExportListOfCompanyData(CompanyList, 1, 1, "Data.txt");
ImportListOfCompanyData("Data.txt", CompanyList, 1, 1);
PrintCompany(CompanyList, 1, 1);
return 0;
}```
It was a really easy solution. I replaced "w" and "r" with "a+"
I guess it was a stupid question, still learning!

When passing through void pointer values changing and getting segmentation fault?

Background: Creating a hash table library which allows 3 different implementations 2 which solve collisions with open addressing (one being of fixed size and the other dynamic) and a 3rd which uses separate chaining with linked lists.
Background to the Problem: Started by creating the fixed size open addressing. At first this worked perfectly, however, had to make some changes to to adapt the library to cater for the other two implementations. For this I needed to record the size of the list (used structures) and void pointers as structures for the open addressing and separate chaining are different.
The Actual Problem: For some reason my save function is no longer working while debugging I've noticed two issues which I cannot discern the cause of:
passing a structure through a void pointer to this function the
values change (please note that this only happens in this functions
and while I uses the same method in the rest of the functions I do
not get the same problem)
I get a segmentation fault on an fprintf statement (that previous to the above mentioned amendments was working.
The Save Function in Question:
void hashtbl_savetofile(void* hashtbl, const char *path){
Hashtbl *temp;
temp = hashtbl;
int i;
FILE *f = fopen(path, "w");
if (f == NULL){
printf("FILE NOT FOUND!");
}else {
for(i = 0; i<SIZE; i++) {
fprintf(f, "%s", temp->data[i].subscript); // segmentation fault occurs
fprintf(f, "%s", temp->data[i].value);
}
fclose(f);
free(temp);
}
}
The Header File:
#ifndef TASK2_HASHTABLE_H
#define TASK2_HASHTABLE_H
#define SIZE 20
#define MAX_LENGTH 100
#define INIT_SIZE 64000
typedef struct Data_struct{
char *subscript;
char *value;
} Data;
typedef struct Hashtbls{
int numberOfEntries;
int allocatedEntries;
Data *data;
}Hashtbl;
int hashtbl_hashKey(void* hashtbl, const char *subscript ); // generates hash key for hash table
Data hashtbl_lookup(void* hashtbl, const char *subscript); //looks up and retrieves a given subscript and its value hash table
void* hashtbl_insert(void* hashtbl, const char *subscript, const char *value); //adds a given subscript and its value to hash table
void* hashtbl_delete(void* hashtbl, const char *subscript); //deletes a given subscript and its value from hash table
void hashtbl_savetofile(void* hashtbl, const char *path); //saves hash table to file
void* hashtbl_loadfromfile(void* hashtbl, const char *path); //loads hash table from file
void* hashtbl_init();
#endif //TASK2_HASHTABLE_H
The Test Driver:
#include <stdio.h>
#include "hashtable.h"
int main() {
Hashtbl *nums;
Data d;
nums = hashtbl_init();
hashtbl_insert(nums, "tea", "40c");
hashtbl_insert(nums, "coffee", "50c");
hashtbl_insert(nums, "biscuit", "4c");
hashtbl_insert(nums, "tart", "30c");
d = hashtbl_lookup(nums, "tart");
printf("%s", d.subscript);
printf("%s", d.value);
hashtbl_savetofile(nums, "test.txt");
}
The Implementation (for reference):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashtable.h"
void* hashtbl_init(){ //initiates static 2D hash table when called
Hashtbl* hashtbl;
hashtbl = malloc(INIT_SIZE);
hashtbl->numberOfEntries = SIZE;
hashtbl->allocatedEntries = 0;
hashtbl->data = calloc(SIZE, sizeof(Data));
for(int i = 0; i<SIZE; i++){
hashtbl->data[i].subscript = malloc(MAX_LENGTH + 1);
strcpy(hashtbl->data[i].subscript, "ZERO\n");
hashtbl->data[i].value = malloc(MAX_LENGTH + 1);
strcpy(hashtbl->data[i].value, "ZERO\n");
}
return hashtbl;
}
Data hashtbl_lookup(void* hashtbl, const char *subscript){
Data item;
Hashtbl *temp;
temp = hashtbl;
int i = 0;
char *c;
c = malloc(MAX_LENGTH);
strcpy(c, subscript);
strct(c, "\n");
while (strcmp(temp->data[(hashtbl_hashKey(hashtbl, subscript)+i)].subscript, c) != 0){
i++;
if(hashtbl_hashKey(hashtbl, subscript)+i == temp->numberOfEntries){
break;
}
}
if(hashtbl_hashKey(hashtbl, subscript)+i != temp->numberOfEntries) {
if(strcmp(temp->data[(hashtbl_hashKey(hashtbl, subscript)+i)].subscript, c) == 0) {
item.subscript = temp->data[(hashtbl_hashKey(hashtbl, subscript) + i)].subscript;
item.value = temp->data[(hashtbl_hashKey(hashtbl, subscript) + i)].value;
}
}else{
for(i = 0; i<hashtbl_hashKey(hashtbl, subscript); i++){
if(strcmp(temp->data[i].subscript, c) == 0){
item.subscript = temp->data[i].subscript;
item.value = temp->data[i].value;
}
}
}
free(hashtbl);
free(c);
free(temp);
return item;//what if not found
}
void* hashtbl_insert(void* hashtbl, const char *subscript, const char *value){
Hashtbl *temp;
temp = hashtbl;
int i = 0;
char *c1;
c1 = malloc(MAX_LENGTH);
strcpy(c1, subscript);
strcat(c1, "\n");
char *c2;
c2 = malloc(MAX_LENGTH);
strcpy(c2, value);
strcat(c2, "\n");
if(temp->allocatedEntries == temp->numberOfEntries){
free(c1);
free(c2);
free(temp);
return hashtbl;
}else {
if (strcmp(temp->data[hashtbl_hashKey(hashtbl, subscript) + i].subscript, "ZERO\n") == 0) {
temp->data[hashtbl_hashKey(hashtbl, subscript)].subscript = c1;
temp->data[hashtbl_hashKey(hashtbl, subscript)].value = c2;
temp->allocatedEntries++;
} else {
while ((strcmp(temp->data[hashtbl_hashKey(hashtbl, subscript) + i].subscript, "ZERO\n") != 0)) {
i++;
if (hashtbl_hashKey(hashtbl, subscript) + i == temp->numberOfEntries) {
break;
}
}
if (hashtbl_hashKey(hashtbl, subscript) + i != temp->numberOfEntries) {
if ((strcmp(temp->data[hashtbl_hashKey(hashtbl, subscript) + i].subscript, "ZERO\n") == 0)) {
temp->data[(hashtbl_hashKey(hashtbl, subscript) + i)].subscript = c1;
temp->data[(hashtbl_hashKey(hashtbl, subscript) + i)].value = c2;
temp->allocatedEntries++;
}
} else {
for (i = 0; i < hashtbl_hashKey(hashtbl, subscript); i++) {
if (strcmp(temp->data[i].subscript, "ZERO\n") == 0) {
temp->data[i].subscript = c1;
temp->data[i].value = c2;
temp->allocatedEntries++;
}
}
}
}
free(c1);
free(c2);
return temp;
}
}
void* hashtbl_delete(void* hashtbl, const char *subscript){
Hashtbl *temp;
temp = hashtbl;
int i = 0;
int j = 0;
char *c;
c = malloc(MAX_LENGTH);
strcpy(c, subscript);
strcat(c, "\n");
while ((strcmp(temp->data[(hashtbl_hashKey(hashtbl, subscript)+i)].subscript, c) != 0)){
i++;
if((hashtbl_hashKey(hashtbl, subscript)+i) == temp->numberOfEntries) {
break;
}
}
if(hashtbl_hashKey(hashtbl, subscript)+i != temp->numberOfEntries) {
if(strcmp(temp->data[(hashtbl_hashKey(hashtbl, subscript)+i)].subscript, c) == 0) {
temp->data[(hashtbl_hashKey(hashtbl, subscript) + i)].subscript = "ZERO\n";
temp->data[(hashtbl_hashKey(hashtbl, subscript) + i)].value = "ZERO\n";
temp->allocatedEntries--;
}
}else{
for(j = 0; j<hashtbl_hashKey(hashtbl, subscript); j++){
if(strcmp(temp->data[j].subscript, c) == 0){
temp->data[j].subscript = "ZERO\n";
temp->data[j].value = "ZERO\n";
temp->allocatedEntries--;
}
}
}
hashtbl=temp;
free(c);
free(temp);
return hashtbl;
}
void hashtbl_savetofile(void* hashtbl, const char *path){
//provided above
}
void* hashtbl_loadfromfile(void* hashtbl, const char *path){
Hashtbl *temp;
temp = hashtbl;
temp->allocatedEntries=0;
int i = 0;
int j =0;
int c = 0;
char line[100];
char* string[temp->numberOfEntries];
FILE *f = fopen(path, "r");
if(f == NULL){
free(temp);
return NULL;
}else {
while(fgets(line, sizeof line, f)){
j++;
}
if((j/2)>temp->numberOfEntries){
free(temp);
return NULL;
}else {
while (fgets(line, sizeof line, f)) {
string[i] = malloc(strlen(line) + 1);
if (string[i] == NULL) {
break;
return NULL;
} else {
strcpy(string[i], line);
i++;
if (i == sizeof string / sizeof *string) {
break;
}
}
}
fclose(f);
for (i = 0; i < (SIZE * 2); i++) {
if (strlen(string[i]) >= MAX_LENGTH) {
char *k = realloc(temp->data[c].subscript, strlen(string[i]));
if (k == NULL) {
break;
return NULL;
} else {
temp->data[c].subscript = k;
strcpy(temp->data[c].subscript, string[i]);
if(temp->data[c].subscript != "ZERO\n"){
temp->allocatedEntries++;
}
i++;
c++;
}
} else {
temp->data[c].subscript = malloc(strlen(string[i]) + 1);
strcpy(temp->data[c].subscript, string[i]);
if(temp->data[c].subscript != "ZERO\n"){
temp->allocatedEntries++;
}
i++;
c++;
}
}
c = 0;
for (i = 1; i < (SIZE * 2); i++) {
if (strlen(string[i]) >= MAX_LENGTH) {
char *k = realloc(temp->data[c].value, strlen(string[i]));
if (k == NULL) {
break;
return NULL;
} else {
temp->data[c].value = k;
strcpy(temp->data[c].value, string[i]);
i++;
c++;
}
} else {
temp->data[c].value = malloc(strlen(string[i]) + 1);
strcpy(temp->data[c].value, string[i]);
i++;
c++;
}
}
hashtbl=temp;
free(temp);
free(string);
return hashtbl;
}
}
}
int hashtbl_hashKey(void* hashtbl, const char *subscript){
int i;
int h = 0;
for(i = 0; subscript[i]; i++){
h += subscript[i];
}
h = h%SIZE;
return h;
}

Only printing last line of txt file when reading into struct array in C

I am reading from a txt file into an array of structures. Example txt:
-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4
The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:
FILE *fileName = NULL;
typedef struct chargeData_struct {
double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;
fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
printf("ERROR: Could not open file.");
}
int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
fclose(fileName);
However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?
You are using an extra semicolon which makes all the trouble, here:
while (fscanf(...) != EOF);
{
...
Remove it and you should be fine.
What happens with your code is that while(..); is equivalent to this:
while(...)
{
; // do nothing
}
thus does not enter the body (the one you think is the body) of your loop (since the actual body does nothing). However scanf() continues to parse the file, and then this section of your code executes:
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
independently, where the curly braces are treated like they wanted to state scope.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LINE_BUFFER_LEN (512)
#define RESERVE_NEWLINDE 0
#define AUTO_FILTER_NEWLINDE 1
typedef int (* LINE_READER)(char * pstrLine, int uiBufferLen, void * pvData);
typedef struct st_HW_SSP_CONFIG
{
const char * pstrConfigPath;
LINE_READER pfLineReader;
FILE * pstFile;
void * pvData;
int CurrentLine;
int Flag;
} CONFIG_ST;
int CloseConfig(CONFIG_ST * pstConfig)
{
if (!pstConfig)
{
// record error
return -1;
}
if (fclose(pstConfig->pstFile))
{
// record error
}
return 0;
}
int OpenConfigFile(const char * pstrFilePath, CONFIG_ST * pstConfig)
{
FILE * pstFile = NULL;
if ((!pstrFilePath) || (!pstConfig))
{
return -1;
}
pstFile = fopen(pstrFilePath, "r");
if (!pstFile)
{
return -1;
}
pstConfig->pstFile = pstFile;
pstConfig->pstrConfigPath = pstrFilePath;
pstConfig->Flag = RESERVE_NEWLINDE;
return 0;
}
int IsNullStr(const char *pcStr)
{
const char *pcTmp = pcStr;
while ('\0' != *pcTmp)
{
if (!isspace(*pcTmp))
{
return 0;
}
pcTmp++;
}
return 1;
}
int IsEffectiveLine(char acFileLineBuffer[LINE_BUFFER_LEN])
{
if (0 == strlen(&acFileLineBuffer[0]))
{
return 0;
}
if ('#' == acFileLineBuffer[0]) // strip as a comment line
{
return 0;
}
if (IsNullStr(&acFileLineBuffer[0]))
{
return 0;
}
return 1;
}
void FilterNewLine(char* pcLine, int MaxNumLen)
{
int uiLen = strlen(pcLine);
if (uiLen > 1)
{
if ('\n' == pcLine[uiLen - 1])
{
pcLine[uiLen - 1] = '\0';
if (uiLen > 2)
{
if ('\r' == pcLine[uiLen - 2])
{
pcLine[uiLen - 2] = '\0';
}
}
}
}
return;
}
int ReadConfigFile(CONFIG_ST * pstConfig)
{
char acFileLineBuffer[LINE_BUFFER_LEN] = {0};
char * pstrRead = NULL;
int Ret = 0;
if (!pstConfig)
{
return -1;
}
if ((!pstConfig->pstFile) || (!pstConfig->pfLineReader))
{
return -1;
}
rewind(pstConfig->pstFile);
pstConfig->CurrentLine = 0;
do
{
memset((void *)&acFileLineBuffer[0], 0, LINE_BUFFER_LEN);
pstrRead = fgets(&acFileLineBuffer[0], LINE_BUFFER_LEN - 1, pstConfig->pstFile);
if (pstrRead)
{
pstConfig->CurrentLine ++;
if (0 == IsEffectiveLine(acFileLineBuffer))
{
continue;
}
if (AUTO_FILTER_NEWLINDE == pstConfig->Flag)
{
FilterNewLine(acFileLineBuffer, LINE_BUFFER_LEN - 1);
}
if (pstConfig->pfLineReader)
{
Ret = pstConfig->pfLineReader(&acFileLineBuffer[0],
LINE_BUFFER_LEN,
pstConfig->pvData);
if (Ret)
{
break;
}
}
}
}
while (pstrRead);
return Ret;
}
int ReadConfigFileEx(const char * pFilePath,
LINE_READER pfReader,
void * pData, int Flag)
{
int Ret = 0;
CONFIG_ST stConfig = {0};
Ret = OpenConfigFile(pFilePath, &stConfig);
if (Ret)
{
return Ret;
}
stConfig.pfLineReader = pfReader;
stConfig.pvData = pData;
stConfig.Flag = Flag;
Ret = ReadConfigFile(&stConfig);
CloseConfig(&stConfig);
return Ret;
}
int StringSplit(char *pcStr, char cFlag,
char * pstArray[], int MaxNum,
int *pNum)
{
char * pcStrTemp = 0;
unsigned int uiIndex = 0;
pcStrTemp = pcStr;
while (pcStrTemp)
{
pstArray[uiIndex] = pcStrTemp;
pcStrTemp = strchr(pcStrTemp, cFlag);
if (pcStrTemp)
{
*pcStrTemp = '\0';
pcStrTemp ++;
uiIndex ++;
}
if (uiIndex >= MaxNum)
{
break;
}
}
if (0 != MaxNum)
{
*pNum = uiIndex >= MaxNum ? (MaxNum - 1) : uiIndex;
}
else
{
*pNum = 0;
}
return 0;
}
int MyLineReader(char * pstrLine, int uiBufferLen, void * pvData)
{
printf("Read line:[%s]\r\n", pstrLine);
char *pArray[8] = {0};
int Num = 0;
int index = 0;
StringSplit(pstrLine, ' ', pArray, 8, &Num);
for (index = 0; index <= Num; index ++)
{
printf("Get value :[%s]\r\n", pArray[index]);
}
return 0;
}
int main(int argc, char * argv[])
{
int ret = 0;
if (argc != 2)
{
printf("Please input file to read.\r\n");
return 0;
}
ret = ReadConfigFileEx(argv[1], MyLineReader, NULL, AUTO_FILTER_NEWLINDE);
if (ret)
{
printf("Open file error.\r\n");
}
return 0;
}

Cannot understand why program crashes after a couple iterations of while loop?

I am writing the following program to parse the text file (attached) but it keeps crashing after couple of iterations of while loop or it seems that the buffer storing file contents is corrupted somehow?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char * pick_question(char *, char, int);
char * print_answer(char *, char, int);
int no_of_questions(char*, char);
void clear();
int debug = 0;
int main(int argc, char* argv[])
{
system("cmd /c chcp 1252");
// system("cmd /c chcp 65001");
if (argc < 2)
{
perror("Please enter a filename!\n");
exit(0);
}
if (argc > 2)
{
debug = atoi(argv[2]);
}
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
if (!file)
{
perror("Unable to read file!\n");
exit(0);
}
else
{
if (debug == 1)
{
printf("File opened successfully\n");
}
}
static char *buffer;
int fileSz;
fseek(file, 0, SEEK_END);
fileSz = ftell(file);
fseek(file, 0, SEEK_SET);
buffer = (char*) malloc((fileSz + 1) * sizeof(char));
if (!buffer)
{
perror("Unable to allocate buffer!");
exit(0);
}
fread(buffer, sizeof(char), fileSz, file);
while (1)
{
time_t t;
srand((unsigned) time(&t));
int sub = rand() % 5 + 1;
char del;
switch (sub)
{
case 1:
del = 'A';
break;
case 2:
del = 'B';
break;
case 3:
del = 'C';
break;
case 4:
del = 'D';
break;
case 5:
del = 'E';
}
int nrOfQues = no_of_questions(buffer, del);
if (nrOfQues == 0)
{
perror("main(): no_of_questions() returned 0. Unsupported text structure in file or incorrect file encoding!");
fclose(file);
exit(0);
}
int qNo = rand() % nrOfQues + 1;
char *ques = pick_question(buffer, del, qNo);
if (ques)
{
printf("\n\n");
puts(ques);
printf("\n\n");
}
else
{
perror("main(): pick_question() returned NULL. Unsupported text structure in file!");
fclose(file);
exit(0);
}
printf("\n\n");
printf("Do you want to see the answer(y/n)?");
char ans, repeat;
scanf("%c", &ans);
if ( ans == 'Y' || ans == 'y')
{
char *ans = print_answer(buffer, del, qNo);
if (ans)
{
printf("\n\n");
puts(ans);
printf("\n\n");
}
else
{
printf("\n\n");
perror("main(): print_answer() returned NULL. Unsupported text structure in file!");
fclose(file);
exit(0);
}
}
printf("Do you want to try more questions (y/n)?");
clear();
scanf("%c", &repeat);
if (repeat == 'N' || repeat == 'n')
{
break;
}
clear();
}
printf("\n\n");
printf("******** Thank you for using TULE Master! ********");
printf("\n\n");
fclose(file);
return 0;
}
char * pick_question(char * buffer, char sub, int qNo)
{
char tmpBuff[20];
char tmpBuff2[20];
const char * searchStr = "FRÅGA";
const char * searchStr2 = "A 1 SVAR:";
const char * searchStr3 = "*****************************************";
char *pStr, *currPos, *nStr, *tmpStr, *tmpStr2;
currPos = buffer;
int count = snprintf(tmpBuff, 20, "FRÅGA %c %d", sub, qNo);
if (count >= 0 || count < 20)
{
if (debug)
{
printf("tmpBuff is %s\n", tmpBuff);
}
currPos = strstr(currPos, tmpBuff);
if (currPos)
{
pStr = currPos;
nStr = currPos + 1;
nStr = strstr(nStr, searchStr);
if (!nStr)
{
nStr = currPos;
nStr = strstr(nStr, searchStr2);
if (!nStr)
{
printf("pick_qestion(): nStr is NULL. Unsupported "
"text structure");
return NULL;
}
}
// Check if it is a scenario based question
count = snprintf(tmpBuff2, 20, "FRÅGA %c %d", sub, qNo-1);
if (count >= 0 || count < 20)
{
tmpStr = strstr(buffer, tmpBuff2);
tmpStr2 = strstr(tmpStr, searchStr3);
if (tmpStr < tmpStr2 && tmpStr2 < pStr)
{
pStr = tmpStr2;
}
}
int qLen = nStr - pStr;
char *ques = malloc(sizeof(char) * (qLen+1));
snprintf(ques,qLen,"%s", pStr);
return ques;
}
else
{
printf("pick_qestion(): string \"FRÅGA\" not found in file!");
return NULL;
}
}
printf("pick_qestion(): snprintf was not successful!");
return NULL;
}
char * print_answer(char * buffer, char sub, int qNo)
{
char tmpBuff[20];
char *pStr, *currPos, *nStr;
int count = snprintf(tmpBuff, 20, "%c %d SVAR:", sub, qNo);
if (count >= 0 || count < 20)
{
currPos = strstr(buffer, tmpBuff);
if (!currPos)
{
printf("print_answer(): string \"SVAR\" not found in file!");
}
pStr = currPos;
nStr = currPos + 1;
char tmpBuff2[20];
int count = snprintf(tmpBuff2, 20, "%c %d SVAR:", sub, qNo+1);
if (count < 0 || count >= 20)
{
printf("print_answer(): snprint was not successful!");
return NULL;
}
nStr = strstr(nStr, tmpBuff2);
if (!nStr)
{
nStr = buffer + strlen(buffer);
}
int ansLen = nStr - pStr;
char *ans = malloc(sizeof(char) * (ansLen+1));
snprintf(ans, ansLen, "%s", pStr);
return ans;
}
printf("print_answer(): snprint was not successful!");
return NULL;
}
int no_of_questions(char *buffer, char sub)
{
char tmpBuff[20];
char *currPos, *pStr;
int count = snprintf(tmpBuff, 20, "FRÅGA %c", sub);
if (count >= 0 || count < 20)
{
if (debug)
{
printf("tmpBuff is %s\n", tmpBuff);
}
currPos = strstr(buffer, tmpBuff);
while (currPos != NULL)
{
pStr = currPos;
currPos = currPos + 1;
currPos = strstr(currPos, tmpBuff);
}
if (pStr != buffer)
{
pStr += 9;
char tmpBuff2[20];
memcpy(tmpBuff2, pStr, 2);
if (debug)
{
printf("No. of questions for %c DEL is are %d\n", sub,
atoi(tmpBuff2));
}
return atoi(tmpBuff2);
}
return 0;
}
return 0;
}
void clear()
{
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
}
This is the file that is given as input to the program:
Link

Pointer to FILE nulling itself without being used at all

in the following code when ran will produce a Segmentation Fault, due to a FILE* being passed to fclose which contains no address (NULL).
I'm wondering why this is happening, the FILE* isn't being used what so over.
The FILE* is named urandom and is passed to fclose in the main function.
Thanks
#include <stdio.h>
#include <stdlib.h>
struct property
{
char *name;
unsigned int value;
unsigned int owner;
unsigned int type;
};
struct player
{
unsigned int id;
unsigned int money;
unsigned int position;
};
int rollDice(FILE *);
int amountOfLines(FILE *);
int createArrayOfPtrs(int ,void ***);
int makeArryOfPropertyPtrs(int ,struct property **);
int FillArryPropertyData(struct property **,int ,FILE *);
int splitBuffer(char *,unsigned int *,char **);
int bufferPropertyFile(FILE *,char **,int );
i nt fillPropertyStruct(struct property *,unsigned int ,char *);
int main(void)
{
int linesInPropertyFile = 0;
struct property **arrayForProperties = 0;
//Open /dev/urandom for rollDice
FILE *urandom = fopen("/dev/urandom","rb");
FILE *propertyFile = fopen("/home/jordan/Documents/Programming/Monopoly Project/properties","rb");
if(propertyFile == NULL || urandom == NULL)
{
puts("ERROR: error in opening file(s)");
return 1;
}
linesInPropertyFile = amountOfLines(propertyFile);
//DEBUG
printf("%d is contained within \"linesInPropertyFile\"\n",linesInPropertyFile);
if(createArrayOfPtrs(linesInPropertyFile,(void ***)&arrayForProperties))
{
puts("ERROR: error from createArrayOfPointers()");
return 1;
}
//DEBUG
printf("Outside Pointer: %p\n",arrayForProperties);
if(makeArryOfPropertyPtrs(linesInPropertyFile,arrayForProperties))
{
puts("ERROR: error from createArrayOfPointersForProperties()");
return 1;
}
if(FillArryPropertyData(arrayForProperties,linesInPropertyFile,propertyFile))
{
puts("ERROR: error from FillArryPropertyData()");
}
//Close FILE stream for /dev/urandom
fclose(urandom);
fclose(propertyFile);
return 0;
}
int FillArryPropertyData(struct property **array,int amntOfProperties,FILE *fp)
{
int bufferUsed = 100;
int i = 0;
int returnValue = 0;
int returnValue2 = 0;
unsigned int money = 0;
char *name;
char *buffer;
rewind(fp);
while(returnValue == 0)
{
buffer = malloc(bufferUsed);
returnValue = bufferPropertyFile(fp,&buffer,bufferUsed);
if(returnValue && returnValue != -1)
{
puts("ERROR: error from bufferPropertyFile()");
return -1;
}
if(returnValue == -1)
{
break;
}
if(buffer[0] != '\0')
{
returnValue2 = splitBuffer(buffer,&money,&name);
}
if(returnValue2)
{
puts("ERROR: error in splitBuffer()");
return 1;
}
if(fillPropertyStruct(array[i],money,name))
{
puts("ERROR: error in fillPropertyStruct()");
return 1;
}
money = 0;
i++;
}
free(buffer);
return 0;
}
int fillPropertyStruct(struct property *array,unsigned int money,char *name)
{
int nameSize = 100;
int i = 0;
array->name = malloc(nameSize);
array->value = money;
while(1)
{
if(i >= nameSize)
{
void *tmp = realloc(array->name,nameSize * 2);
nameSize *= 2;
if(tmp)
{
array->name = tmp;
}
else
{
return -1;
}
}
if(name[i] == '\0')
{
break;
}
array->name[i] = name[i];
i++;
}
array->name[i] = '\0';
return 0;
}
int splitBuffer(char *buffer,unsigned int *money,char **name)
{
int i = 0;
int j = 1;
int nameSize = 100;
*name = malloc(nameSize);
while(1)
{
if(buffer[j] != '"')
{
(*name)[j-1] = buffer[j];
}
else
{
i++;
}
j++;
if(i)
{
break;
}
if(j >= nameSize)
{
void *tmp = 0;
tmp = realloc(*name,nameSize * 2);
nameSize = nameSize * 2;
if(tmp != NULL)
{
*name = tmp;
}
else
{
puts("ERROR: error in splitBuffer");
return -1;
}
}
}
name[j-1] = '\0';
while(buffer[j] != '$')
{
if(buffer[j] == '\0')
{
puts("ERROR: error in splitBuffer()");
return -2;
}
j++;
}
j++;
while(buffer[j] != '\0')
{
*money += (buffer[j] - '0');
if(buffer[j+1] != '\0')
{
*money *= 10;
}
j++;
}
printf("BUFFER: %s\n",buffer);
printf("NAME: %s\n",*name);
printf("MONEY: %d\n",*money);
return 0;
}
int bufferPropertyFile(FILE *fp,char **buffer,int i)
{
int j = (i - i);
if(feof(fp))
{
//-1 Returned if EOF detected
return -1;
}
char retr = 0;
while(1)
{
if(j + 1 >= i)
{
void *tmp = realloc(*buffer,i * 2);
if(tmp != NULL)
{
*buffer = tmp;
i = i * 2;
}
else
{
puts("ERROR: error in bufferPropertyFile()");
return -2;
}
}
retr = fgetc(fp);
if(retr == '\n' || feof(fp))
{
break;
}
(*buffer)[j] = retr;
j++;
}
(*buffer)[j] = '\0';
if(**buffer == '\0')
{
return -1;
}
return 0;
}
int rollDice(FILE *fp)
{
int seed = fgetc(fp);
srand(seed);
return (rand() % 6) + 1;
}
int amountOfLines(FILE *file)
{
int i = 0;
int retr = 0;
while(1)
{
retr = fgetc(file);
if(retr == EOF)
{
break;
}
if(retr == '\n' )
{
i++;
}
}
return i;
}
int createArrayOfPtrs(int numberOfPointers,void ***pointer)
{
void *tmp = malloc(numberOfPointers * sizeof (tmp));
if(tmp != NULL)
{
*pointer = tmp;
//DEBUG
printf("Pointer: %p\n",*pointer);
}
else
{
return 1;
}
return 0;
}
int makeArryOfPropertyPtrs(int numberOfPointers,struct property **pointer)
{
int i = 0;
void *tmp;
for(i = 0;i < numberOfPointers;i++)
{
tmp = malloc(sizeof(struct property));
if(tmp == NULL)
{
return 1;
}
pointer[i] = (struct property *)tmp;
}
return 0;
}
here it givest an access violation in splitBuffer on this line:
name[j-1]='\0';
which probably should be
(*name)[j-1]='\0';
indeed that memory is not allocated anywhere, in other words, undefined behaviour, which indeed in your case might overwrite the urandom variable: both urandom and name are allocated on stack so depending on value of j it might write over urandom..
apart from that, there might be more errors, the number and use of pointers/mallocs/reallocs and lack of frees is a bit scary
int createArrayOfPtrs(int ,void ***);
if(createArrayOfPtrs(linesInPropertyFile,(void ***)&arrayForProperties))
This is undefined behaviour, a (void***) is not compatible to a (struct property ***). Why do you even use it here, all the other functions use struct property pointers?
Since the array is located right before the file pointer in the local variables of main, maybe the problem is that the array creation/initialization overwrites urandom?

Resources