【发布时间】:2015-08-28 07:38:40
【问题描述】:
到此为止,我真的束手无策:)
我基本上是在尝试设置一个包含未确定大小的数组的 struct Foo,然后让单独的函数设置所述数组的值并打印它。但是,当我尝试打印时,我在 valgrind 中不断收到“条件跳转或移动取决于未初始化的值”和“使用大小为 8 的未初始化值”错误。
这里是代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Foo {
char *name;
int x;
int y;
int *array; //this is the problematic array
};
struct Foo *foo_maker(char *name, int x, int y, int array_size)
{
int array[array_size];
memset(array, 0, sizeof(array)); //initializing the array here, so why am i getting the errors?
struct Foo *a_foo = malloc(sizeof(struct Foo) + sizeof(array));
a_foo->name = name;
a_foo->x = x;
a_foo->y = y;
a_foo->array = array;
return a_foo;
}
void set_foo(struct Foo *a_foo, int array_size)
{
int i;
for(i = 0; i < array_size; i++)
a_foo->array[i] = 1;
}
void print_foo(struct Foo *a_foo, int array_size)
{
int i;
for(i = 0; i < array_size; i++)
printf("%d\n", a_foo->array[i]);
}
void foo_killer(struct Foo *a_foo)
{
free(a_foo);
}
int main(int argc, char *argv[])
{
char *name = argv[1];
int x = atoi(argv[2]);
int y = atoi(argv[3]);
int array_size = atoi(argv[4]);
struct Foo *foo = foo_maker(name, x, y, array_size);
set_foo(foo, array_size);
print_foo(foo, array_size);
foo_killer(foo);
return 0;
}
我认为将 a_foo->array 作为参数传递给其他函数没有问题,因为只有当我尝试打印数组时才会遇到未初始化的错误。我什至尝试在 foo_maker 和 set_foo 中打印数组,但两次都遇到了同样的错误。
任何帮助将不胜感激:)
【问题讨论】: