C:malloc 似乎分配的比我请求的多(数组) [英] C : malloc seems to allocate more then i'm requesting (array)

查看:12
本文介绍了C:malloc 似乎分配的比我请求的多(数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有这个问题:为什么当我使用 malloc 为浮点数组分配内存时,它会分配我请求的更多空间?例如,在这段代码中,我试图分配一个十个单元"浮点数组,但是如果我尝试访问其他单元,它不会返回任何段错误:

Hi I have this question: Why when I'm allocating memory with malloc for a float array, it allocate more space that i'm requesting? For example in this code i'm trying to allocate a ten "cells" float array, but if I try to access to other cells it returns me no segfault error:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

float *fk_array;

int main(int argc, char** argv){


    fk_array = (float *) malloc(10 * sizeof(float));
    int i;
    fk_array[9] = 2.23;
    fk_array[15] = 0.3;
    for(i = 0; i<20 ; i++)
        printf("%f
",fk_array[i]);
    free(fk_array);

    return 1;
}

它返回我:

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
2.230000
0.000000
0.000000
0.000000
0.000000
0.000000
0.300000
0.000000
0.000000
0.000000
0.000000

我哪里错了??

推荐答案

当调用 malloc 时,可能会使用额外的空间来存储有关已分配块的元数据,例如其大小和有关其他已分配块的信息.有时,实现更喜欢以特定间隔分配块(例如,4 或 8 字节的倍数).但是,您不应该依赖每次调用 malloc 时空间量是否一致;仅使用您特别要求的内容,否则您可能会覆盖其他重要信息.

When calling malloc, additional space may used to store metadata about the allocated block, such as its size and information about other allocated blocks. Sometimes the implementation prefers allocated blocks to be at specific intervals (e.g., multiples of 4 or 8 bytes). However, you shouldn't depend on the amount of space being consistent each time you call malloc; use only what you have specifically requested or you may be overwriting other important information.

有关更多信息,请参阅以下问题的答案:

See the answers to the following questions for more information:

这篇关于C:malloc 似乎分配的比我请求的多(数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆