【发布时间】:2019-09-25 12:35:44
【问题描述】:
我被指派为我们的学校辩护制定一个有效的学生选举计划(并且可能用于实际用途......)。但是,我已经被一个问题困扰了一段时间了。
我的目标是创建一个灵活的结构数组,因为我不能使用任意限制,而且数组对我来说也有 99 个项目的限制(*见帖子末尾)。我使用了 realloc() 但它为无效的旧大小提供了 abort() 。但是,我已经尝试在另一个程序中测试一个动态结构数组,它工作得完美无缺。我不知道是什么导致另一个崩溃。
我的选举计划(即崩溃的计划):
注意:entr_cmd 函数只是将光标移动到屏幕底部并打印一个文本,而 STREQL 只是查看两个字符串是否匹配,只是 strcmp 的快捷宏
struct candidate {
long lrn;
char *name;
int grade;
char *section;
char *party;
char *position;
}
**candidates,
// :: Temporary Array for storing all the candidates in the position to be voted in
**candidates_cur;
int can_c = 0;
[...]
int main() {
[...]
candidates = malloc(2 * sizeof(struct candidate *));
[...]
if(STREQL(command, "c")) {
struct candidate *c;
if(can_c > 1) {
struct candidate **tmp;
tmp = (struct candidate**) realloc(candidates, (1 + can_c) * sizeof(struct candidate *));
if(tmp != NULL) candidates = tmp;
}
candidates[can_c - 1] = malloc(sizeof(struct candidate *));
c = candidates[can_c - 1];
entr_cmd("Candidate's Name: ");
// :: This recieves the input but replaced for testing
c->name = malloc(4 * sizeof(char));
strcpy(c->name, "XXX");
can_c++;
}
[...]
完美运行的测试程序:
这会为测试结构的成员生成一个随机数字字符串
struct test {
char *name;
char *another;
int test;
} **arr;
int main() {
int r1;
arr = malloc(2 * sizeof(struct test *));
r1 = rand() % 45;
for(int i = 0; i < r1; i++) {
int r2 = rand() % 22;
if(i > 2) {
struct test **data;
data = (struct test**) realloc(arr, (2 + i) * sizeof(struct test*));
if(data != NULL) {
arr = data;
}
}
arr[i] = malloc(sizeof(struct test *));
struct test *t = arr[i];
t->name = malloc(r2 * sizeof(char));
t->another = malloc(r2 * sizeof(char));
t->test = r2;
for(int ii = 0; ii < r2; ii++) {
t->name[ii] = (char) (rand() % 9) + '0';
t->another[ii] = (char) (rand() % 9) + '0';
}
printf("====[%u]====\n%s\n%s\n%u\n", i, arr[i] -> name, arr[i] -> another, arr[i] -> test);
}
for(int i = 0; i < r1; i++) {
free(arr[i]->name);
free(arr[i]->another);
free(arr[i]);
}
free(arr);
getch();
}
任何帮助都将不胜感激,因为我们的老师对我寄予厚望,并告诉我这会很容易容易,但事实证明恰恰相反。
感谢您的阅读,祝您有愉快的一天!!!
额外的废话:我在一个我们经常使用 TurboC++ 进行编程的课程中,但在那里很难做到这一点,所以我在我的 Neovim 设置中使用了 C99,这样我就可以快速导航和C99 中的大部分内容也可以在 TurboC++ 中运行。换句话说,我不能真正使用(最近的标准)C++,如果是这样,我想我可能会更容易做到这一点
【问题讨论】:
-
通过 valgrind 运行您的代码。如果你的内存管理不善,它会告诉你在哪里。
-
int can_c = 0;后跟candidates[can_c - 1]让我非常警惕。 -
@JulianoDavidHilario 如果你以
myprog arg1 arg2 ...运行你的程序,那么你在valgrind 下以valgrind myprog arg1 arg2 ...运行它。输出包括读取未初始化内存、在 malloc 内存边界之外读取/写入以及内存泄漏等内容。 -
@Someprogrammerdude 哇!我修好了它!谢谢!!!这是因为我的 malloc 超出范围 XD。它是-1
-
评论
candidates[can_c - 1] = malloc(sizeof(struct candidate *));考虑candidates[can_c - 1] = malloc(sizeof *(candidates[can_c - 1]));
标签: c arrays malloc c99 realloc