如何修复strcat函数中的分段错误?

时间:2018-04-22 14:46:31

标签: c struct function-pointers

我正在尝试使用函数指针作为C结构的成员。我有Identity,Person和RandomPeople类型。我的程序以“程序已停止工作”结束。我用gdb调试了我的程序,我有以下输出。

[New Thread 18028.0x2c28]
[New Thread 18028.0x4150]
enter the number of people:2
Program received signal SIGSEGV, Segmentation fault.
0x754c5619 in strcat () from C:\WINDOWS\SysWOW64\msvcrt.dll

RandomPeople.h 中可能strcat

这是我的计划: Identity struct可以创建标识号并检查给定的标识号。

Identity.h 档案:

#ifndef Identity_H
#define Identity_H
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

struct IDNO {
    char *(*CreateIDNo)(struct IDNO *);   
};

typedef struct IDNO *Id;
Id CreateID();
char *CreateIDNo(Id this);
#endif

Identity.c 文件:

#include "Identity.h"

char *CreateIDNo(Id this) { 
    int str[11]; 
    int totalodd = 0;
    int totaleven = 0;
    this->id = "";

    for (int i = 1; i < 12; i++) {           
        if (i == 1) {
            int n = 1 + rand() % 9;
            totalodd += n;
            str[i - 1] = n;
            continue;
        } else
        if (i != 1 && i % 2 == 0 && i < 10) {
            int n = rand() % 10;
            totaleven += n;
            str[i - 1] = n;
            continue;
        } else
        if (i != 1 && i % 2 != 0 && i < 10) {
            int n = rand() %10;
            totalodd += n;
            str[i - 1] = n;
            continue;
        } else
        if (i == 10) {
            int n11 = (7 * totalodd - totaleven) % 10;
            str[i - 1] = n11;
            continue;
        } else
        if (i == 11) {
            int n12 = (totalodd + totaleven + str[9]) % 10;
            str[i - 1] = n12;
            continue;
        }      
    }
    for (int i = 0; i < 11; i++) {
        char *b; 
        itoa(str[i], b, 10);
        strcat(this->id, b);
    }
    return this->id;
}

每个Person都有Identity引用,可以使用此引用创建标识号。

Person.h 档案:

#ifndef PERSON_H
#define PERSON_H
#include "Identity.h"

struct PERSON {
    Id superid;
};

typedef struct PERSON *Person;
Person CreatePerson();
#endif

Person.c 档案:

#include "Person.h"

Person CreatePerson() {
    Person this;
    this = (Person)malloc(sizeof(struct PERSON));
    this->superid = CreateID();  //Creating my reference    
    return this;
}

RandomPeople.c 文件:

#include "RandomPeople.h"

void CreateRandomPeopleData(RandomPeople k) {
    Person person = CreatePerson();
    char *formatted_identity = person->superid->CreateIDNo(person->superid);
    strcat(data, formatted_identity);       
}   

test.c 文件

int main() {
    RandomPeople rastgelekisiler = CreateRandomPeople();
    rastgelekisiler->CreateRandomPeopleData(rastgelekisiler);
    return 0;
}

编辑:我把这些结构放在我的问题上,因为分段问题可能出现在这些函数指针体中。这些函数可能返回可能指向错误位置的char指针或null。我认为这个问题有最小,完整和可验证的例子。我不希望被投票。

1 个答案:

答案 0 :(得分:0)

您以这种方式初始化 Identity.c 中的>>> soup.select_one('li.test > a') <a>link1</a> this->id

this->id = "";将尝试无法写入字符串文字strcat(this->id, b)的只读存储空间。

顺便说一句,""在传递给b时未初始化,这是另一个未定义行为的计数。

相关问题