【发布时间】:2018-04-22 14:46:30
【问题描述】:
我正在尝试将函数指针用作 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;
}
编辑:我将这些结构放在我的问题上,因为分段问题可能出现在这些函数指针体中。这些函数可能会返回可能指向错误位置或 null 的 char 指针。我认为这个问题具有最小、完整和可验证的示例。我不希望被否决。
【问题讨论】:
-
这不是我所说的Minimal, Complete, and Verifiable Example。请尝试将代码缩小到仍然存在问题的最小部分。请记住,如果您想在
strcat调用中将指针用作目标,则指针需要实际指向可以写入数据的位置。 -
哦,
scanf("%s", ...)期望输入什么?变量input是什么?"%s"格式和input匹配吗? -
谢谢。我把这些结构放在我的问题上,因为分段问题可能出现在这些函数指针体中。(我从这些函数指针中收集随机数据(字符指针)。)
-
四种可能:(1)您正在调用
strcat(a, b),其中a或b是空指针; (2) 您正在调用strcat(a, b),其中a或b是垃圾值(不指向任何地方); (3)b指向不是正确的以空字符结尾的字符串的字符; (4)a指向一个不足以容纳连接字符串的内存区域。 (在这种情况下,4 的可能性较小。) -
请阅读minimal reproducible example底部链接的“调试小程序”页面。另外,请考虑minimal reproducible example中的“minimal”这个词。
标签: c struct function-pointers