c - 为什么代码 1 出现段错误?

标签 c dynamic-memory-allocation file-read file-pointer

代码1:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main(int argc,char **argv)
{
    FILE *fp;
    char lineBuf[100],**p=NULL,temp[100];
    int cnt,j,i;
    if(argc!=2)
    {
        puts("ERROR:Invalid no.of arguments");
        return;
    }
    fp=fopen(argv[1],"r");
    if(fp==NULL)
    {
        printf("'%s' file doesn't exist\n",argv[1]);
    }
    cnt=0;

    while(fgets(lineBuf,100,fp))  //...........loop1
    {
        cnt++;
        p=realloc(p,sizeof(char*)*(cnt));
        if(p==NULL)
        {
            puts("memory unavailable");
            return;
        }

        p[cnt-1]=calloc(1,strlen(lineBuf));
        strcpy(p[cnt-1],lineBuf); //................statement1
    }

    fclose(fp);
    for(i=0;i<cnt;i++)
    {
        for(j=i+1;j<cnt;j++)
        {
            if(strcmp(p[i],p[j])>0)
            {
                strcpy(temp,p[i]);
                strcpy(p[i],p[j]);
                strcpy(p[j],temp);
            }
        }
    }

    fp=fopen(argv[1],"w");
    for(i=0;i<cnt;i++)
        fputs(p[i],fp);
    fclose(fp);
    puts("sorting done");
}

代码2:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main(int argc,char **argv)
{
    FILE *fp;
    char lineBuf[100],**p=NULL,temp[100];
    int cnt,j,i;
    if(argc!=2)
    {
        puts("ERROR:Invalid no.of arguments");
        return;
    }
    fp=fopen(argv[1],"r");
    if(fp==NULL)
    {
        printf("'%s' file doesn't exist\n",argv[1]);
    }
    cnt=0;

    while(fgets(lineBuf,100,fp)) //........loop2
    {
        cnt++;
        p=realloc(p,sizeof(char*)*(cnt));
        if(p==NULL)
        {
            puts("memory unavailable");
            return;
        }

        p[cnt-1]=calloc(1,strlen(lineBuf));

    }
    rewind(fp);

    for(i=0;fgets(lineBuf,100,fp);i++) //........loop3
    {
       strcpy(p[i],lineBuf);//..........statement1
    }
    fclose(fp);
    for(i=0;i<cnt;i++)
    {
        for(j=i+1;j<cnt;j++)
        {
            if(strcmp(p[i],p[j])>0)
            {
                strcpy(temp,p[i]);
                strcpy(p[i],p[j]);
                strcpy(p[j],temp);
            }
        }
    }
    fp=fopen(argv[1],"w");
    for(i=0;i<cnt;i++)
        fputs(p[i],fp);
    fclose(fp);
    puts("sorting done");
}

我已经编写了用于对文件中的行进行排序的代码。我已将文件的每一行复制到动态分配的内存中。在循环1中,如果我编写语句1,则会出现段错误或内存不可用。所以我修改并编写了CODE2。在这里我得到了正确的输出。

I want to know, what is happening in loop1.

我正在从文件中获取数据并在同一循环中复制到动态分配的内存中。同时进行分配和复制是否错误?

最佳答案

strcpy(p[i],lineBuf);

i 从未在第一个代码片段中初始化

关于c - 为什么代码 1 出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27425929/

相关文章:

c - 使用 strtok 标记数字列表的程序中的错误 0Xc0000005

c - 如果在单独的线程中关闭(2) 文件描述符,select(2) 会做什么?

c - 为什么使用 Dev-C++ 编译器而不是 Visual Studio 的编译器进行编译?

c - 使用递归读入一行并返回指向该字符串的指针

c++ - 如何从文件中读取值。分词器

python - 在python中读取一个pgm文件

c - 结构字符串数组打印最后输入的元素

c++ - 模板类构造函数中的动态分配

c - 将文本文件转换为动态结构数组 C 编程

c - 使用 fgets 从文件中读取