Having trouble figuring out why I run into a segmentation fault with the longer piece of code.
I take this and run it fine.
struct Earthquake
{
char *prevString;
char *magString;
char *postString;
};
int main(void)
{
struct Earthquake eq;
eq.prevString="PREVIOUS STRING";
eq.magString = "50";
eq.postString = "POST STRING";
printf("\n%s",eq.prevString);
printf("\n%s",eq.magString);
printf("\n%s\n",eq.postString);
}
When I try to run this I get a segmentation fault, which I stop getting if I comment out the struct initialization. You might be able to tell with what I have commented out, but once I get this working I'm trying to make a struct array at which point I know the eq needs to be an Earthquake pointer but I can't even get this working.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#include <stddef.h>
//#include <paths.h>
struct Earthquake
{
char *prevString;
char *magString;
char *postString;
};
int main()
{
int numLines = 0;
FILE *fileA = fopen("./all_month.csv", "r");
char c[1];
do
{
*c = fgetc(fileA);
//printf("%c", c);
}while(*c != '\n');
do
{
*c = fgetc(fileA);
//printf("%c", c);
if(*c == '\n')
{
numLines++;
}
}while(*c != EOF);
//printf("%d",numLines);
fclose(fileA);
FILE *fileB = fopen("./all_month.csv", "r");
char prevStringTemp[60];
char postStringTemp[150];
char magStringTemp[10];
struct Earthquake eq;
//if(NULL == (entries = (Earthquake *)malloc(sizeof(Earthquake) * numLines)));
//printf("\nmalloc failed\n");
do
{
*c = fgetc(fileB);
//printf("%c", c);
}while(*c != '\n');
char line[200];
int commaCount = 0;
do{
*c = fgetc(fileB);
if(*c==',')
{
commaCount++;
//printf("\n%d", commaCount);
}
strcat(prevStringTemp, c);
}while(commaCount<4);
do
{
*c = fgetc(fileB);
strcat(magStringTemp, c);
}while(*c!=',');
do
{
*c = fgetc(fileB);
strcat(postStringTemp, c);
}while(*c!='\n');
//strcpy(entries[0].prevString, prevString);
//printf(entries[0].prevString);
//fscanf(fileB,"%s",line);
//printf("\n%s\n", line);
fclose(fileB);
//free(entries);
return 0;
}
This is the problem
strcat(prevStringTemp, c);
beacause strcat()
expects nul
terminated strings which niether the parameters is in your case.
Your c
array should be
char c[2] = {0};
and the first element of these
char prevStringTemp[60];
char postStringTemp[150];
char magStringTemp[10];
should be initialized to '\\0'
, like this
prevStringTemp[0] = '\0';
postStringTemp[0] = '\0';
magStringTemp[0] = '\0';
after fixing this, strcat()
will behave as you expect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.