-3

代码 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。在这里,我得到了正确的输出。

我想知道,loop1发生了什么。

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

4

3 回答 3

7
strcpy(p[i],lineBuf);

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

于 2014-12-11T15:08:50.340 回答
4

我认为calloc(1, strlen(lineBuf))必须是calloc(1, 1 + strlen(lineBuf)),因为您没有考虑终止null字节'\0'

于 2014-12-11T15:08:36.343 回答
2
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

You check for fp to be NULL but then continue on to use it.

于 2014-12-11T15:11:29.223 回答