Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why segmentation fault?

0 votes
asked Dec 9, 2018 by Francesco
this code goes in segmentation fault, does any expert know why?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 4

char **get_frase(int);
char *get_parola();
void frase_to_file(char **, int, char *[], char *);

int main(int argc, char *argv[]){
  int tot_parole;
  char **frase;
  char *dataset[N] = {"franco", "mauro", "maria", "antonio"};

  printf("tot parole: ");
  scanf("%d", &tot_parole);

  frase = get_frase(tot_parole);

  printf("ciao");

  frase_to_file(frase, tot_parole, dataset, argv[1]);
}

char **get_frase(int tot_parole){
  char **frase;

  frase = calloc(tot_parole, sizeof(char *));

  for(int i=0; i<tot_parole; i++){
    frase[i] = get_parola();
  }

  return frase;
}

char *get_parola(){
  char word[100]; //prova con *
  char *parola;

  printf("\nInserisci: ");
  scanf("%s", word);

  parola = calloc(strlen(word) + 1, sizeof(char));
  strcpy(parola, word);

  return parola;
}

void frase_to_file(char **frase, int tot_parole, char *dataset[], char *file_name){
  FILE *my_file = fopen(file_name, "w");

  for(int i=0; i < tot_parole; i++){
    for(int j=0; i<N; i++){
      if(!strcmp(frase[i], dataset[j])){
        fprintf(my_file, "%s\n", frase[i]);
        break;
      }
    }
  }
  fclose(my_file);
}

1 Answer

0 votes
answered Dec 13, 2018 by anonymous
It seems the problem is in declaring 'frase' as pointer to pointer to char where as it was supposed to be pointer to char only.
After makin frase as char* it seems to be working fine.
Here is updated code : https://onlinegdb.com/HyN5fZlxN
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...