如何摆脱分段错误:11

时间:2015-10-16 16:31:18

标签: c segmentation-fault

我知道可能存在大量其他问题,但在我发现分段错误消失之前,我无法解决问题。我很确定这与我使用mallocs有关,但我不确定它究竟来自哪里。我还是新编码,所以任何其他建议也表示赞赏。我正在使用的测试文件只是一行,上面写着“快速的棕色狐狸跳过懒惰的老狗”,但它应该可以用于任何事情。所有其他信息都应该在代码注释中。

//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;
}

2 个答案:

答案 0 :(得分:2)

FILE *fp = fopen("argv[2]","r");   

应该是 -

FILE *fp = fopen(argv[2],"r");   
if(fp==NULL)
      printf("error in opening file");

您再次将words指向temp,因此您先前使用malloc松散了对分配给它的内存的引用。请注意以前分配的内存不会被释放。

在函数char getString (FILE *fp)中,您将char *s内存分配为sizeof(int)。是故意的吗?

答案 1 :(得分:0)

解决了ameyCu指出的问题后,就有了这个

 if (feof(fp)) break;

由于文件结束标记仅在 I / O操作之后设置,因此不能按照您的想法执行操作。在feof(fp)之后立即检查fopen,您无法检测到空文件。您必须检查每个输入操作的成功,即每个fgetc