Linux下用C语言实现#一个返回字符串的函数


=Start=

缘由:

在Linux上需要用C语言实现一个函数用于根据指定参数获取当前时间对应格式字符串的函数(注:直接返回固定内容的字符串的函数不在此讨论范围内)。但是C语言中函数内的变量是有生命周期的,需要用malloc动态分配内存以防止函数返回时变量失效;另一个方法就是直接在被调用处申请,不过这样的话调用起来就没那么方便;还有一个办法就是在函数内对变量用static关键字进行限定,不过这样就无法编写可重入(re-entrant)的函数了。

好久没用C语言写这类程序了,不太好把握,所以去网上搜索了一下,把看到的比较好的内容总结了一下,方便以后参考。

正文:

参考解答:

在网上搜索了一下,其实我要的这个函数和 getwd() 以及 get_current_dir_name() 的功能很像:

char *getwd(char *buf);	// For portability and security reasons, use of getwd() is deprecated.
char *get_current_dir_name(void);
	get_current_dir_name() will malloc(3) an array big enough to hold the absolute pathname of the current working directory. If the environment variable PWD is set, and its value is correct, then that value will be returned. The caller should free(3) the returned buffer.

我的需求:实现一个根据参数返回当前时间对应格式字符串的函数。这样的功能,一般情况下,建议是在 function 中调用 malloc 动态分配内存,然后在 caller 那里负责进行使用(call)和释放(free)。

/* 方法一:调用者负责分配内存 */
/* OK: caller allocates the memory */
char buf[512];
char * my_func(char* ret) /* called with "buf" */
{
  strcpy(ret, some_get_a_string_func()); /* assign the string pointer */
  return ret;
}

/* 方法二:合法但是该函数不可重入 */
/* Legal ... but not re-entrant.  
   Every call to "my_func()" will step on every other call.
   Definitely *NOT* OK with threads; probably not OK anywhere else  */
char * my_func()
{
  static char buf[512];
  strcpy(buf, some_get_a_string_func()); /* assign the string pointer */
  return buf;
}

/* 方法三:被调用函数分配内存,调用函数需要记得释放对应内存 */
/* Also OK: callee allocates memory; caller (or SOMEBODY!) needs to remember to free it. */
char * my_func(int max_bytes)
{
  char *buf = malloc (max_bytes + 1);
  if (buf)
  {
    /* assign string pointer 
       protect against buffer overflow
       insure return string is always NULL, or zero-terminated */
    strncpy(buf, some_get_a_string_func(), max_bytes); 
    buf[max_bytes] = '\0';
  }
  return buf ;
}
参考链接:

=END=

, ,

《“Linux下用C语言实现#一个返回字符串的函数”》 有 3 条评论

  1. const 和 static 的作用 #Nice
    http://www.cnblogs.com/HappyXie/archive/2012/08/27/2658282.html
    `
    隐藏作用域——限制在本文件范围内;
    保持变量内容的持久(在程序刚开始运行时就完成初始化,也是唯一的一次初始化);
    默认初始化为0,其实全局变量也具备这一属性,因为全局变量也存储在静态数据区;
    `
    https://stackoverflow.com/questions/572547/what-does-static-mean
    https://en.wikipedia.org/wiki/Static_(keyword)
    https://softwareengineering.stackexchange.com/questions/250126/static-vs-non-static-with-non-oop-functions

    C语言中Static和Const关键字的的作用
    http://www.cnblogs.com/hellocby/p/3543989.html

    C/C++中static、const的区别
    http://blog.csdn.net/firefly_2002/article/details/8045078

    C++的const和static的用法
    http://www.cnblogs.com/10jschen/archive/2012/09/22/2698102.html

回复 a-z 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注