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

查看:87
本文介绍了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\n",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:

  • How do free and malloc work in C?
  • Why does malloc allocate a different number of bytes than requested?

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

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