c - 为什么函数调用会导致段错误?

标签 c segmentation-fault

请告诉我为什么这个函数调用会导致段错误

看看代码的第二部分,第一部分没有错误,我已经调试过了

向下滚动到第二个代码片段

#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);

最佳答案

在函数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++;
}

最后一行与任何下一行都不匹配...

关于c - 为什么函数调用会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13612412/

相关文章:

python - 识别使用 Cython 生成的 C 代码中的 C 函数

c - 我如何修复显示的超出文件大小限制的消息

c - 在另一个函数中修改 char* ? (分段故障)

c - 制作我自己的 strlen 函数,以接收字符串作为链接列表

c++ - 实现队列类,段错误?

c++ - 如何修复 strlen 段错误

c - RPC 函数返回结构;客户值(value)观垃圾

c - 覆盖变量实际上是如何工作的?

c - 这两行代码中的显式和隐式类型转换有什么区别?

c - 赛格夫 : invalig write of size 8 when adding a node to the end of a linked list