i'm trying to read values from a .csv file and write them in another .txt file. But when i'm trying to pass the values it creates a Segmentation fault.
My first program, which filters the needed values from the .csv file:
int main(int argc, char **argv) {
if (argc < 3) {
printf("Aufruf: %s <anzahl> <bundesland>\n", argv[0]);
printf("Beispiel: %s 100 Bayern\n", argv[0]);
printf("Klein-/Großschreibung beachten!\n");
exit(1);
}
int anzahl = atoi(argv[1]);
char *bundesland = argv[2];
// Statisch allokierter Speicher
char staedte[MAX_LAENGE_ARR][MAX_LAENGE_STR];
char laender[MAX_LAENGE_ARR][MAX_LAENGE_STR];
int bewohner[MAX_LAENGE_ARR];
int len = read_file("staedte.csv", staedte, laender, bewohner);
// Hier implementieren
char** result = malloc(MAX_LAENGE_ARR * sizeof(char *));
if (result == NULL) {
perror("malloc failed while allocating memory");
exit(1);
}
for (int i = 0; i < len; i++) {
if (strcmp(bundesland, laender[i]) == 0 && *bewohner > anzahl) {
result[i] = malloc(MAX_LAENGE_STR * sizeof(char *));
if (result == NULL) {
perror("malloc failed while allocating memory");
exit(1);
}
snprintf(result[i], MAX_LAENGE_STR, "Die Stadt %s hat %d Einwohner.", staedte[i], bewohner[i]);
write_file(&result[i], len);
free(result[i]);
}
}
// Mithilfe von write_file(...) soll das Ergebnis in die "resultat.txt"
// geschrieben werden.
// Dynamisch allozierter Speicher muss hier freigegeben werden.
}
And the faulting part of my second program, which should write the handed values from the first program into a .txt file:
int MAX_LAENGE_STR = 255;
int MAX_LAENGE_ARR = 100;
void write_file(char *result[], int len) {
FILE *fp = fopen("resultat.txt", "w");
if (fp == NULL){
perror("resultat.txt");
exit(1);
}
for (int i=0; i<len; i++) {
printf("<write_file> loop[%d]: %s\n", i, result[i]);
fprintf(fp, "%p\n", result[i]);
}
fclose(fp);
}
It creates a Segmentation fault in the 11th loop, in the write_file(), and i can't figure out why. In valgrind it's: "Invalid read size of 1".
MAX*sizeof(char*)when creating buffer for a string, useMAX*sizeof(char).*bewohner > anzahl?*bewohneris the first element of your int arraybewohnerso same asbewohner[0]. Is that really what you want to compare? Maybebewohner[i]but I don't know your logic here.printf("%s", result[i]);. But when trying to hand over the values to the second program and write those values into a txt file it crashes with the segmentation fault. And i'm not allowed to change the second program due to my prof, because thats my limitation.gcc -Wall -Wextra -gwith GCC. Improve your code to get no warnings. Use the debuggergdb