0
我真的在我束手无策这里:)打印一个结构
我基本上是试图建立一个结构美孚包含未确定大小的数组内任意大小的数组,然后有单独的fuctions设定的值所述数组并打印它。但是,当我尝试打印时,我不断在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->数组作为参数传递给其他fuctions一个问题,因为它是唯一的,当我尝试当我打印阵列获取未初始化的错误。我甚至尝试在foo_maker和set_foo中打印数组,并且两次都得到相同的错误。
任何帮助,将不胜感激:)
谢谢! 因此,如果我使用malloc来设置数组,然后将其分配给a_foo-> array,那会起作用吗?我很困惑,因为我认为使用'a_foo->数组'符号的重点是我可以给它赋值并且即使在堆栈之外也会粘住,因为'a_foo-> array'指向堆中的某个区域? – drunkenlollipop
你也可以看一下'calloc',它是为初始化分配给'0'的内存块量身定做的。在数组情况下,这可防止无意尝试从未初始化的值读取数据。 –
您需要区分'struct foo'中指针“int * array”的4个字节的内存与指针指向的内存。指针值,指向另一个内存的_where所在的内存将超出此函数。但是你所指向的内存区域不再存在,因为如果你只是做int array [array_size],内存区域就是函数堆栈的一部分; –