C程序分段错误main()

C程序分段错误main(),c,segmentation-fault,argv,argc,C,Segmentation Fault,Argv,Argc,我是C编程的新手,我已经根据需求规范编写了一段代码,但我总是遇到分段错误,无法继续。 如果文件名为“code.c”,并且运行时出现错误,即未传递参数(文件名)。但是如果文件名被传递,我们就陷入了分段错误。 如有任何帮助/建议,将不胜感激 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> struct _data {

我是C编程的新手,我已经根据需求规范编写了一段代码,但我总是遇到分段错误,无法继续。 如果文件名为“code.c”,并且运行时出现错误,即未传递参数(文件名)。但是如果文件名被传递,我们就陷入了分段错误。 如有任何帮助/建议,将不胜感激

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



struct _data 
{               
   char *firstName;
   char *lastName;
   long number;
}; 

// SCAN FILE
int SCAN(FILE *(*stream))
{
    *stream = fopen("inputFile.data", "r");

    int ch = 0, lines = 0;

    while (!feof(*stream))
    {
        ch = fgetc(*stream);
        if (ch == '\n')
        {
            lines++;
        }
    }
    return lines;
}

// LOAD FILE
struct _data *LOAD(FILE *stream, int size) 
{
    int i;
    size_t chrCount;
    char *text, *number, *firstName, *lastName;
    struct _data *BlackBox;

    if ((BlackBox = (struct _data*)calloc(size, sizeof(struct _data))) == NULL) 
    {
          printf("ERROR - Could not allocate memory.\n");
          exit(0);
    }

    rewind(stream);


    for (i = 0; i < size; i++) 
    {
        getline(&text, &chrCount, stream);
        firstName   = strtok(text, " ");
        lastName    = strtok(text, " ");
        number      = strtok(NULL, "\n");

        // Allocate memory for name part of struct.
        if ((BlackBox[i].firstName = (char*)calloc(strlen(firstName), sizeof(char))) == NULL) 
        {
           printf("ERROR - Could not allocate memory.\n");
           exit(0);
        }
        if ((BlackBox[i].lastName = (char*)calloc(strlen(lastName), sizeof(char))) == NULL)
        {
           printf("ERROR - Could not allocate memory.\n");
           exit(0);
        }

        strcpy(BlackBox[i].firstName, firstName);
        strcpy(BlackBox[i].lastName, lastName);
        BlackBox[i].number = atol(number);
    }
    fclose(stream);
    return BlackBox;
}


void SEARCH(struct _data *BlackBox, char *name, int size, int inputs) 
{
    int i;
    int found = 0;
    char *search = " ";
    char *firstName;
    char *lastName; 

    if (inputs == 2)
    {
        firstName = strtok(name, search);
        lastName = strtok(NULL, search);
    }


    printf("*******************************************\n");
    if (inputs == 2)
    {   
        for (i = 0; i < size; i++) 
        {          
            if (!strcasecmp(firstName, BlackBox[i].firstName) && !strcasecmp(firstName, BlackBox[i].firstName))
            {
                printf("The name was found at the %d entry.\n", i);
                found = 1;
                break;
            }
        }
    }
    else
    {
        for (i = 0; i < size; i++) 
        {          
            if (!strcasecmp(firstName, BlackBox[i].firstName) || !strcasecmp(firstName, BlackBox[i].firstName))
            {
                printf("The name was found at the %d entry.\n", i);
                found = 1;
                break;
            }
        }
    }

    if (found == 0) 
    {
          printf("The name was NOT found.\n");
    }
    printf("*******************************************\n");
}

// FREE MEMORY
void FREE(struct _data *BlackBox, int size) 
{
    int i;
    for (i = 0; i < size; i++) 
    {
        free(BlackBox[i].firstName);
        free(BlackBox[i].lastName);
    } 
    free(BlackBox);
    BlackBox = NULL;
}


// MAIN
int main(int argv, char **argc) 
{
    int size;
    FILE *stream;
    struct _data *BlackBox;

    // argv == 1 WORKS, Below message is printed.
    if (argv == 1) 
    {          
        printf("*******************************************\n");
        printf("* You must include a name to search for.  *\n");
        printf("*******************************************\n");
    }
    // argv == 2 DOES NOT WORK, Segmentation Fault.     
    if (argv == 2) 
    {
        size = SCAN (&stream);
        BlackBox = LOAD(stream, size);
        SEARCH(BlackBox, argc[1], size, 1);
    }
    if (argv == 3) 
    {
        size = SCAN(&stream);
        BlackBox = LOAD(stream, size);
        SEARCH(BlackBox, argc[2], size, 2);
    }
    return 0;
}
#包括
#包括
#包括
#包括
结构数据
{               
char*名字;
char*lastName;
长数;
}; 
//扫描文件
整数扫描(文件*(*流))
{
*stream=fopen(“inputFile.data”,“r”);
int ch=0,线条=0;
而(!feof(*stream))
{
ch=fgetc(*流);
如果(ch='\n')
{
行++;
}
}
回流线;
}
//加载文件
结构数据*加载(文件*流,整数大小)
{
int i;
大小和数量;
字符*文本,*数字,*名字,*姓氏;
结构数据*黑盒;
if((BlackBox=(struct\u data*)calloc(size,sizeof(struct\u data)))==NULL)
{
printf(“错误-无法分配内存。\n”);
出口(0);
}
倒带(流);
对于(i=0;i
此代码中存在问题:

    firstName   = strtok(text, " ");
    lastName    = strtok(text, " ");
    number      = strtok(NULL, "\n");

第二个
strtok()
调用应传递
NULL
作为其第一个参数。实际上,第三个
strtok()
调用肯定会返回
NULL
,因为第一个调用修改
text
的方式是第二个调用消耗整个内容(当从一开始再次标记时,这是错误的)。但是,您不需要对此进行测试,因此,
atol()
尝试取消对空指针的引用

更新

此外,正如@chqrlie和后来的@JamesWilkins所观察到的,您没有为
BlackBox[i].firstName
BlackBox[i].lastName分配足够的空间,因为您还需要为字符串终止符分配空间。这是一个完全独立的问题,也可能产生segfault。我喜欢@chqrlie建议切换到
strdup()
,但只需将每个分配增加一个单位就足够了

更新2

此外,您对这一行有疑问:

    getline(&text, &chrCount, stream);
在第一次调用之前,您不会初始化变量
text
,因此它包含一个垃圾值。函数仅在其第一个参数指向空指针时分配缓冲区;否则,它会将行写入通过取消引用第一个参数获得的指针指向的缓冲区。写入内存中的随机位置肯定会产生未定义的行为,这在实践中通常表现为错误

此外,除非您可以相信文件的任何一行都不会比第一行长,否则您还需要在每个循环迭代结束时释放
文本
指针,并将其值重置为
NULL
,以便
getline()
在下一个itera上分配新的缓冲区
    getline(&text, &chrCount, stream);
#include <iostream>

using namespace std;

struct _data
{
    char *firstName;
    char *lastName;
    long number;
};

// SCAN FILE
int SCAN(FILE *(*stream))
{
    *stream = fopen("inputFile.data", "r");
    if (*stream == NULL)
    {
        perror("Error opening file");
        return 0;
    }

    char ch = 0, lines = 0, linesize = 0;

    while ((ch = fgetc(*stream)) != EOF)
    {
        if (ch == '\n')
        {
            lines++;
            linesize = 0;
        }
        else linesize++;
    }

    if (linesize > 0)
        lines++; // (last line doesn't have '\n')

    return lines;
}

// LOAD FILE
struct _data *LOAD(FILE *stream, int lineCount)
{
    int i;
    size_t chrCount = 256;
    char text[256], *result, *number, *firstName, *lastName;
    struct _data *BlackBox;

    if ((BlackBox = (struct _data*)calloc(lineCount, sizeof(struct _data))) == NULL)
    {
        printf("ERROR - Could not allocate memory.\n");
        exit(0);
    }
    else memset(BlackBox, 0, sizeof(struct _data) * lineCount); // (make sure all data members are null to begin)

    rewind(stream);


    for (i = 0; i < lineCount; i++)
    {
        result = fgets(text, chrCount, stream);
        if (result == NULL)
            break; // (EOF)

        firstName = strtok(text, " ");
        lastName = strtok(NULL, " ");
        number = strtok(NULL, "\n");

        // Allocate memory for name part of struct.
        if ((BlackBox[i].firstName = (char*)calloc(strlen(firstName) + 1, sizeof(char))) == NULL)
        {
            printf("ERROR - Could not allocate memory.\n");
            exit(0);
        }
        if ((BlackBox[i].lastName = (char*)calloc(strlen(lastName) + 1, sizeof(char))) == NULL)
        {
            printf("ERROR - Could not allocate memory.\n");
            exit(0);
        }

        strcpy(BlackBox[i].firstName, firstName);
        strcpy(BlackBox[i].lastName, lastName);
        BlackBox[i].number = atol(number);
    }

    fclose(stream);

    return BlackBox;
}


void SEARCH(struct _data *BlackBox, char **names, int lineCount, int inputs)
{
    int i, l;
    int found = 0;

    printf("*******************************************\n");

    for (i = 0; i < inputs; ++i)
    {
        for (l = 0; l < lineCount; ++l)
        {
            if (BlackBox[l].firstName != NULL && !_stricmp(names[i], BlackBox[l].firstName)
                || BlackBox[l].lastName != NULL && !_stricmp(names[i], BlackBox[l].lastName))
            {
                printf("The name was found on line %d.\n", 1 + l);
                found = 1;
                break;
            }
        }
        if (found) break;
    }

    if (!found)
        printf("The name was NOT found.\n");

    printf("*******************************************\n");
}

// FREE MEMORY
void FREE(struct _data *BlackBox, int lineCount)
{
    int i;
    for (i = 0; i < lineCount; i++)
    {
        if (BlackBox[i].firstName != NULL)
            free(BlackBox[i].firstName);
        if (BlackBox[i].lastName != NULL)
            free(BlackBox[i].lastName);
    }
    free(BlackBox);
}


// MAIN
int main(int argc, char **argv)
{
    int lineCount;
    FILE *stream;
    struct _data *BlackBox;

    // argc == 1 WORKS, Below message is printed.
    if (argc == 1)
    {
        printf("*******************************************\n");
        printf("* You must include a name to search for.  *\n");
        printf("*******************************************\n");
    }
    // argc == 2 DOES NOT WORK, Segmentation Fault.     
    if (argc > 1)
    {
        lineCount = SCAN(&stream);
        if (lineCount > 0)
        {
            BlackBox = LOAD(stream, lineCount);
            SEARCH(BlackBox, argv + 1, lineCount, argc - 1);
            FREE(BlackBox, lineCount);
        }
    }
    return 0;
}