Я знаю, что есть, вероятно, проблемы с другими проблемами, но я не могу устранить неполадки до тех пор, пока у меня не исчезнет ошибка сегментации. Я почти уверен, что это связано с моим использованием mallocs, но я не уверен, откуда именно это происходит. Я все еще новичок в кодировании, поэтому любые другие советы также приветствуются. Тестовый файл, который я использую, - это всего лишь одна строка, которая гласит: «Быстрая коричневая лиса прыгает через ленивую старую собаку», но она должна работать на что угодно. Вся остальная информация должна быть в аннотациях кода.Как избавиться от ошибки сегментации: 11
//This program is supposed to act as line justification formater.
//When running the program, the user will specify what justification
//type they want (either left, right, or center) and the column width.
//The program will output the text of the file broken up over several
//and justified appropriately.
#include <stdio.h>
#include "scanner.h"
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
FILE *fp = fopen("argv[2]","r");
int checkArguments(char[],int); //function declarations
char getString (FILE *);
int justify(char,int,int,char **);
char *justif=argv[4]; //these two variables hold the width and length
char *widthC=argv[3]; //that the user puts in when they run the function
int width=atoi(widthC);
int wordsSum=0; //this variable holds the total number of wordis
int i;
checkArguments(justif,width);
char **words = malloc(sizeof(char *)*1); //this string will hold each word as a token
for (i=0;;i++){
if (feof(fp)) break;
else {
char **temp;
wordsSum++;
temp=realloc(words,(i+1)*sizeof(char*));
if(temp!=NULL){ //this reallocates the memory for words
words=temp; //and if the reallocation was succsesful
char tempString=getString(fp); //gives words a new token
words[i]=&tempString;
i++;
}
else {
free(words);
printf("Malloc error :c\n");
return 0;
}
}
}
justify(*justif,width,wordsSum,words);
fclose(fp);
return 0;
}
/*This program does two simple checks to make sure the user put in valid widths and lengths */
int checkArguments(char a[], int width){
if (!(strcmp(a,"right")==0 || strcmp(a,"left")==0 || strcmp(a,"center")==0)){
printf("You did not enter a possible justification, please try again.");
exit(0);
}
else if(width<=0){
printf("You did not enter a possible width, please try again.");
exit(0);
}
else return 0;
}
/*This program reads the file and stores characters of one word inside a malloc string
It then does a malloc realocation check and, if sucsessful, returns the word*/
char getString (FILE *fp){
char c;
int i;
char *s=malloc(sizeof(int));
char *temp;
for (i=0;;i++) {
c=fgetc(fp);
if (c==' ' || c=='\n')
break;
s[i]=c;
temp=realloc(s,(i+1)*sizeof(int));
if(temp!=NULL){
s=temp;
}
else {
free(s);
printf("Malloc error :c\n");
return 0;
}
}
return *s;
}
/*This function will eventually have another if else statement at the beggining, and
print different amounts of spaces in the beggining of the line depending on what
justification the user wants. For now it assumes left justified.*/
int justify(char justif, int width, int wordsSum, char ** words){
int i=0,j=0,k=0;
while(i<wordsSum) //while there are more words to print
{
while(j<=width) //while not at the maximum width for lines
{
if(j+strlen(words[i])<=width){ //find if adding another word would put
j+=strlen(words[i]); //the line width over the maximum width
i++; //if no, add another word
}
else{ //if yes, print the current line
for (k=0;k<=j;k++)
printf ("%s",words[k]);
printf("\n");
j=0; //reset the line length to zero
}
}
}
return 0;
}
Почему вы объявляете функции внутри 'main'? –
Вы пытаетесь открыть файл с именем * '' argv [2] "'. Если это не удастся, тогда 'fopen' вернет нулевой указатель, что вы, похоже, не проверяете. –
Должен ли я сделать указатель на argv [2], а затем открыть файл для этого указателя? –