这是一个可接受的malloc示例吗?

时间:2012-07-04 14:31:00

标签: c arrays dynamic

以下代码是否可以接受。也就是说,这是做malloc的正确方法吗?

这是我可以为我的情况工作的最小代码。我认为这是'正确的做法',但我对C来说是超级新手并且没有太多线索。我阅读了几个相关的SO帖子,但似乎没有一个完全符合这种情况。评论

#include <stdio.h>

// example of calling a function that creates a dynamically sized array and
// returns it to a caller that doesn't know or care about the size of the array

char* return_char_array(){
     // for the sake of the example, we determined the size to be 100
     char *f=malloc(100*sizeof(char));
     // stick something in the first couple of elements for test purposes
     *f=65;
     *(f+1)=66;
     return f;
}

int main(){
    // we want this function to remain ignorant of the size or other workings 
    // of the array, so, no '[]' or 'malloc'
    char *wipc = return_char_array();
    // well i guess it cares a little, because we assume there are at least 2 elements...
    printf("%c,%c\n",*(wipc),*(wipc+1));
    system("PAUSE");
    return 0;
}

7 个答案:

答案 0 :(得分:4)

  

评论

使用f[0]代替*ff[1]代替*(f + 1)。同样适用于wipc。不要忘记致电free

答案 1 :(得分:1)

我认为在这种情况下可以。 但请记住释放分配的内存:)

答案 2 :(得分:0)

任何函数都没有任何优势,不知道它正在使用的数组的大小。评论需要解释。

答案 3 :(得分:0)

在第一眼看到我承认你没有释放()你的malloced空间,这是坏事(记忆泄漏)。这是我能看到的唯一真正的“错误”。但是,如果您希望以Code-Review的形式获得更多信息,可以将其发布在Stackexchange站点“Code-Review”上,因为本站点更能解决实际问题和错误。

答案 4 :(得分:0)

嗯,它真的是最小的代码。 我宁愿把额外的标记字节放在缓冲区的末尾,并记得在malloc

时将额外的2个字节添加到缓冲区长度。

这两个字节保留供内部使用,不应向用户公开。

答案 5 :(得分:0)

不,这不是一个坏主意,没有多大意义。分配内存的代码需要负责释放它,否则你将有很大的内存泄漏潜力。

通常你会写这样的算法:

// caller.c

#include "stuff.h"  // the code uses the code module "stuff"

void caller (void)
{
  int* array = malloc(N * sizeof(int));

  do_stuff(array, N);

  free(array);
}

_

// stuff.h

void do_stuff (int* array, int size);

_

// stuff.c

#include "stuff.h"

void do_stuff (int* array, int size)
{
  ...
}

通过这个程序设计,“do_stuff()”不需要关心内存分配,它只是执行它的算法。也没有人担心内存泄漏,因为分配和释放是在同一个地方完成的。

此外,通过这种设计,do_stuff()与静态分配的内存(简单数组)一样好。

这种设计几乎是C中的标准。整个Windows API使用这种设计作为一个例子。

答案 6 :(得分:0)

一些评论,

1)PL。做适当的错误处理。如果malloc失败会发生什么?

char *f=malloc(100*sizeof(char))
if (NULL == f)
{   
   //Take actions ..Exit with error or return NULL..
}

2)PL。避免像100这样的硬编码值(可能有#define MAX 100)

3)PL。确保正确释放内存。

相关问题