问题描述
我想用malloc
在函数内分配内存,然后返回缓冲区。然后,我希望能够从函数外部将一个字符串strcpy
插入该缓冲区。
这是我当前的代码
#include <stdlib.h>
#include <string.h>
char allocate_mem(void) {
char *buff = malloc(124); // no cast is required; its C
return buff // return *buff ?
}
int main(int argc,char const *argv[])
{
char buff = allocate_mem();
strcpy(buff,"Hello World");
free(buff);
return 0;
}
// gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
解决方法
您的allocate_mem
创建了char *
,但随后返回了char
。
返回char*
并将其存储为char *buff
,其余的代码也可以正常工作。
函数中的变量buff
具有类型char *
。因此,如果要返回指针,则该函数必须具有返回类型char *
。
char * allocate_mem(void) {
char *buff = malloc(124); // no cast is required; its C
return buff // return *buff ?
}
主要是你必须写
char *buff = allocate_mem();
请注意,在函数中使用幻数124
并不是一个好主意。
更有意义的功能可能看起来如下
char * allocate_mem( const char *s ) {
char *buff = malloc( strlen( s ) + 1 ); // no cast is required; its C
if ( buff ) strcpy( buff,s );
return buff // return *buff ?
}
主要可以写
char *buff = allocate_mem( "Hello World" );
//...
free(buff);
另一种方法是将整数值用作参数,该整数值将指定分配的内存的大小。例如
char * allocate_mem( size_t n ) {
char *buff = malloc( n ); // no cast is required; its C
return buff // return *buff ?
}