首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解malloc()

理解malloc()
EN

Stack Overflow用户
提问于 2014-07-05 21:05:22
回答 1查看 277关注 0票数 2
代码语言:javascript
复制
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;

下面的代码是在主函数中编写的。当我将heap_fourints指针转换为char*时,我不明白为什么编译器没有给出错误,或者程序由于断言而停止。

代码语言:javascript
复制
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);

我认为这是正确的实施。

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-05 21:16:07

代码语言:javascript
复制
FourInts* heap_fourints=malloc(sizeof(FourInts) * 4);

这将分配足够的内存来保存结构的4副本(每个足够容纳4个整数),这是一个足够至少容纳16个整数的内存。虽然您没有使用所有这些内存,但是您从来没有在它之后进行读写,所以运行时是愉快的(没有内存损坏)。

OTOH

代码语言:javascript
复制
FourInts* heap_fourints=malloc(sizeof(int) * 4); // int, not ints(!)

将分配足够的内存来保存4的值。注:这并不一定意味着由于可能的对齐填充(然而,在int情况下不太可能),这个内存足以容纳4个整数的结构。

但是再次--在您的平台上,您也没有用第二段代码侵犯内存。

至于编译器错误,或者更确切地说是缺少这些错误。C不是像其他语言那样强类型的语言(例如C++),指针转换的规则也比较宽松。一种类型的变量指向的内存可以自由地转换为另一种类型。当然,这是非常危险的(而且是不鼓励的),尽管它有它的用途。特别是在处理极低级别的代码时。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24590555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档