用C内存分配 [英] memory allocation in C

查看:145
本文介绍了用C内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于内存分配秩序的问题。
在下面的code我分配在一个循环4串。
但是,当我打印的地址,他们似乎没有被分配一前一后...我是不是做错了什么或者是某种防御机制由操作系统prevent可能的缓冲区溢出实施? (我使用Windows Vista)。

感谢您。

 的char ** stringArr;
 INT大小= 4,I; stringArr =(字符**)的malloc(大小* sizeof的(字符*));
 对于(i = 0; I<大小;我++)
    stringArr [I] =(字符*)malloc的(10 * sizeof的(炭)); 的strcpy(stringArr [0],ABCDEFGH);
 的strcpy(stringArr [1],好运气);
 的strcpy(stringArr [2],mully);
 的strcpy(stringArr [3],斯塔姆); 对于(i = 0; I<大小;我++){
  的printf(%S \\ n,stringArr [I]);
  的printf(%d个%u \\ n \\ n,及(stringArr [I]),stringArr [I]);
 }

输出:


  

ABCDEFGH
  9650064 9650128


  
  

好运气
  9650068 9638624


  
  

mully
  9650072 9638680


  
  

斯塔姆
  9650076 9638736



解决方案

通常情况下,当你通过请求内存的malloc(),C运行时库将圆的大小的要求到某个最小分配大小。这可以确保:


  • 的运行时库室的记录信息

  • 这对运行时库来管理分配块的一些大小的倍数更有效(如16字节)

不过,这些都是实现细节,你不能真正依靠任何特定行为的malloc()

I have a question regarding memory allocation order. In the following code I allocate in a loop 4 strings. But when I print the addresses they don't seem to be allocated one after the other... Am I doing something wrong or is it some sort of defense mechanism implemented by the OS to prevent possible buffer overflows? (I use Windows Vista).

Thank you.

 char **stringArr;
 int size=4, i;

 stringArr=(char**)malloc(size*sizeof(char*));
 for (i=0; i<size; i++)
    stringArr[i]=(char*)malloc(10*sizeof(char));

 strcpy(stringArr[0], "abcdefgh");
 strcpy(stringArr[1], "good-luck");
 strcpy(stringArr[2], "mully");
 strcpy(stringArr[3], "stam");

 for (i=0; i<size; i++) {
  printf("%s\n", stringArr[i]);
  printf("%d  %u\n\n", &(stringArr[i]), stringArr[i]);
 }

Output:

abcdefgh 9650064 9650128

good-luck 9650068 9638624

mully 9650072 9638680

stam 9650076 9638736

解决方案

Typically when you request memory through malloc(), the C runtime library will round the size of your request up to some minimum allocation size. This makes sure that:

  • the runtime library has room for its bookkeeping information
  • it's more efficient for the runtime library to manage allocated blocks that are all multiples of some size (such as 16 bytes)

However, these are implementation details and you can't really rely on any particular behaviour of malloc().

这篇关于用C内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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