一道malloc的面试题,大家帮忙看看

nuclears 2005-08-01 05:11:23
去一家公司面试。有一道面试题是这样的:要求分配11个字节的空间,是个填空题:
……malloc(________);
前面的我省略了,就是返回值什么的。
我不知道考这道题的具体用意是什么,我直接写了个“11”,不知道对不对。

谁能给我讲讲吗?malloc这个函数用的时候,申请的空间的长度有什么规则吗?
...全文
541 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
xixiaboy 2005-08-02
  • 打赏
  • 举报
回复
对直接写11还要犹豫吗?
soft_biao 2005-08-01
  • 打赏
  • 举报
回复
直接11就可以了
hafent 2005-08-01
  • 打赏
  • 举报
回复
malloc(sizeof(byte)*11)

这个是奇数个字节,会不会要考虑内存对齐呀
malloc(sizeof(byte)*12)
jixingzhong 2005-08-01
  • 打赏
  • 举报
回复
晕 写完帖子上面就那么多人了 ...
jixingzhong 2005-08-01
  • 打赏
  • 举报
回复
char *s=(char*)malloc(11);


理论上是可以的

但是 malloc 前面的 东西没有给定

这么写也许会有问题的



可以这样

……malloc(sizeof(char)*11);

这样也有局限性

虽然现在的 char 一般都是一个字节

但是 也许会有意外发生

即使现在没有 也不能保证以后也没有 ...
ningzhiyu 2005-08-01
  • 打赏
  • 举报
回复
malloc是按byte为基本单位分配内存的。
直接11就应该可以了。
可以在网上搜索一下malloc看看,有很多解释的
PMsg 2005-08-01
  • 打赏
  • 举报
回复
Example

/* MALLOC.C: This program allocates memory with
* malloc, then frees the memory with free.
*/

#include <stdlib.h> /* For _MAX_PATH definition */
#include <stdio.h>
#include <malloc.h>

void main( void )
{
char *string;

/* Allocate space for a path name */
string = malloc( _MAX_PATH );

// In a C++ file, explicitly cast malloc's return. For example,
// string = (char *)malloc( _MAX_PATH );

if( string == NULL )
printf( "Insufficient memory available\n" );
else
{
printf( "Memory space allocated for path name\n" );
free( string );
printf( "Memory freed\n" );
}
}
benjiam 2005-08-01
  • 打赏
  • 举报
回复
sizeof(char)*11
everestsun 2005-08-01
  • 打赏
  • 举报
回复
char *s=(char*)malloc(11);
xuanwenchao 2005-08-01
  • 打赏
  • 举报
回复
……malloc(11);
zaisheng09 2005-08-01
  • 打赏
  • 举报
回复
11字节空间段的首地址。
fireman_lh 2005-08-01
  • 打赏
  • 举报
回复
BYTE[11]

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧