void fillArray(int* array, int len) {
printf("Filling an array at address %p with %d "
"values\n", array, len);
int i=0;
for (i = 0; i < len; ++i) {
array[i] = i * 3 + 2;
// assert() verifies that the given condition is true
// and exits the program otherwise. This is just a
// "sanity check" to make sure that the line of code
// above is doing what we intend.
assert(array[i] == i * 3 + 2);
}
printf("Done!\n");
}
typedef struct {
int a, b, c, d;
} FourInts;
下面的代码是在main函数中编写的。我无法理解为什么当我将 heap_fourints 指针转换为 char* 时,编译器没有给出错误或程序由于断言而停止。
FourInts* heap_fourints=malloc(sizeof(FourInts) * 4);
fillArray( (char*) heap_fourints,4);
assert((*heap_fourints).a == 2);
assert(heap_fourints->b == 5);
assert(heap_fourints->c == 8);
assert(heap_fourints->d == 11);
我认为这是正确的实现。
FourInts* heap_fourints=malloc(sizeof(ints) * 4);
fillArray( (ints*) heap_fourints,4);
assert((*heap_fourints).a == 2);
assert(heap_fourints->b == 5);
assert(heap_fourints->c == 8);
assert(heap_fourints->d == 11);
最佳答案
FourInts* heap_fourints=malloc(sizeof(FourInts) * 4);
这将分配足够的内存来保存结构的 4
个副本(每个副本足以保存 4 个整数),该内存足以至少 16 个整数。尽管您没有使用所有这些内存,但您从未读/写超出它的内容,因此运行时很高兴(没有内存损坏)。
奥托
FourInts* heap_fourints=malloc(sizeof(int) * 4); // int, not ints(!)
将分配足够的内存来保存4 int
值。注意:这并不必然意味着由于可能的对齐填充,该内存足以容纳具有 4 个整数的结构(但是,在 int
的情况下,这不是很重要)可能)。
但再次强调 - 在您的平台上,您的第二个代码也不会违反内存。
至于编译器错误,或者说缺少这些错误。 C
不像其他一些语言(例如 C++
)那样是强类型语言,并且指针转换的规则有些宽松。一种类型的变量指向的内存可以自由地转换为另一种类型。当然,尽管它有其用途,但这是非常危险的(并且不鼓励)。特别是在处理极低级代码时
关于c - 了解 malloc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24590555/