0

この関数呼び出しでセグメンテーション違反が発生する理由を誰か教えてください

コードの 2 番目のセクションを見てください。最初のセクションにはエラーがありません。既にデバッグ済みです。

2 番目のコード スニペットまで下にスクロールします

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"line.h"
main(int argc,char **argv,...)
{
  FILE *fp;
  char ch,**str=0;
  int length=0,maxlen=0,line=0;

  if(argc==2)
  fp=fopen(argv[1],"r");

  else
  {
   printf("Expexted Input Was:\"./linesort\" \"filename\"\n");
   return;
  }

  if(fp==NULL)
  {
   printf("Source file not found ,Please Check If It Really Exists in Expected path\n");
   return;
  }

   printf("%ld:",ftell(fp));

  while((ch=fgetc(fp))!=EOF)
  {
     length=0;
     while(ch!='\n')
     {
     printf("%c",ch);
     ch=fgetc(fp);
     length++;
     }

    printf("len:%d\n",length);
    if(maxlen<length)
    maxlen=length;
    line++;
  }

printf("maxlen:%d\n",maxlen);
printf("No.of lines:%d\n",line);
fseek(fp,0,0);
str=(char **)malloc(line*sizeof(char *));
printf("__%ld____\n",str);

for(length=0;length<line;length++)
{
 printf("%d\t",length);
 str[length]=malloc((maxlen+1)*sizeof(char));
 printf("__%ld____\n",str[length]);
 fgets(str[length],maxlen+1,fp);
 puts(str[length]);
}

fclose(fp);

while(1)
{
   printf(" \n'a':for alphabet wise \t'c':for character wise\t 'e':to exit:\t");
   ch=getchar();
   getchar();

///////このセクションはセグメンテーション違反を引き起こし、次のコードは前のコードの続きです

alpha(str,maxlen,line); を見てください。

   switch(ch)
   {
      case 'a':  alpha(str,maxlen,line);///////////Causes Segmentation Fault?Why?
                 break;
    //case 'c':chara(str);
    //    break;
    case 'e':exit(0);
    default :;
   }
   }
 }

//// alpha.c(呼び出された関数はこのファイルにあります)このセクションに論理エラーがあっても気にしないでください

   #include"line.h"
   void alpha(char **p,int maxlen,int line)
    {
     int i=0;
     char *buffer;
     printf("in alpha");
     buffer = (char *)malloc((maxlen+1)*sizeof(char));
     while(i<line)
     {
      if(strcmp(p[i],p[i+1])==+1)
      {
        strcpy(buffer,p[i+1]);
         strcpy(p[i+1],p[i]);
         strcpy(p[i],buffer);
        }
      i++;
     }
      printf("%s\t",p[3]);
     }

///////私のヘッダーファイル (line.h) にはこれらの宣言が含まれています

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void alpha(char **p,int maxlen,int line);
void chara(char **p,int maxlen,int line);
4

2 に答える 2

1

関数内alpha():

while(i < (line - 1))
{
    if(strcmp(p[i],p[i+1])==+1)
    {
        strcpy(buffer,p[i+1]);
        strcpy(p[i+1],p[i]);
        strcpy(p[i],buffer);
    }
    i++;
}

最終行が次の行と一致しません...

于 2012-11-28T19:29:21.430 に答える
0

Eclipse または Visual Studio で新しい C プロジェクトを作成し、デバッガーを実行します。最後に実行された行を確認します。デバッガーで変数を調べて、無効なものとその原因を確認します。

また、開くはずのファイルに入力例を投稿していません。

于 2012-11-28T19:21:54.797 に答える