由strdup及strndup想到的一些问题
时间:2007-05-16 来源:greentown
这个函数在linux的man手册里解释为:
The strdup() function returns a pointer to a new string which is a
duplicate of the string s. Memory for the new string is obtained with
malloc(3), and can be freed with free(3). The strndup() function is similar, but only copies at most n charac-
ters. If s is longer than n, only n characters are copied, and a termi-
nating NUL is added. 这里有一个问题就是strdup函数返回的字符串指针是由malloc在函数内部分配的,那么谁来释放这个动态内存呢? 程序员?还是系统?呵呵,真得很难回答。个人关点是这种做法尽量避免,函数内申请动态内存,而在函数外让程序员来释放,不过每个人都有每个人的观点,呵呵,下面是一个测试例子(无错误处理机制):
#include <stdio.h>
#include <stdlib.h>
#include <string.h> unsigned int Test()
{
char buf[]="Hello,World!";
char* pb = strndup(buf,strlen(buf));
return (unsigned int)(pb);
} int main()
{
unsigned int pch = Test();
printf("Testing:%s\n", (char*)pch);
free((void*)pch);
return 0;
}
在Test函数里使用strndup而出了Test函数仍可以操作这段内存,并且可以释放。 由这个问题而延伸出来的问题就是,如何让函数得到的内存数据传出函数但仍可用。 解决方法目前本人只想到两个,一个外部变量,如传递一个内存块指针给函数,但这种做法就是你得传递足够的内存,也就是你不能事先知道这个函数到底要多大的BUFFER。另一种方法就是在函数内部申请static变量,当然这也是全局区的变量,但这种做法的缺点就是,当函数多次运行时,static变量里面的数据会被覆盖。这种类型的另一个方法就是使用全局变量,但这和使用static变量很相同,不同的是全局变量可以操作控制,而static变量如果不把它传出函数,就不可对它操作控制了。 另一类方法就是上面所述的,利用堆里的内存来实现,但存在危险,~_~。 至于其他的方法,目前还没想到。
duplicate of the string s. Memory for the new string is obtained with
malloc(3), and can be freed with free(3). The strndup() function is similar, but only copies at most n charac-
ters. If s is longer than n, only n characters are copied, and a termi-
nating NUL is added. 这里有一个问题就是strdup函数返回的字符串指针是由malloc在函数内部分配的,那么谁来释放这个动态内存呢? 程序员?还是系统?呵呵,真得很难回答。个人关点是这种做法尽量避免,函数内申请动态内存,而在函数外让程序员来释放,不过每个人都有每个人的观点,呵呵,下面是一个测试例子(无错误处理机制):
#include <stdio.h>
#include <stdlib.h>
#include <string.h> unsigned int Test()
{
char buf[]="Hello,World!";
char* pb = strndup(buf,strlen(buf));
return (unsigned int)(pb);
} int main()
{
unsigned int pch = Test();
printf("Testing:%s\n", (char*)pch);
free((void*)pch);
return 0;
}
在Test函数里使用strndup而出了Test函数仍可以操作这段内存,并且可以释放。 由这个问题而延伸出来的问题就是,如何让函数得到的内存数据传出函数但仍可用。 解决方法目前本人只想到两个,一个外部变量,如传递一个内存块指针给函数,但这种做法就是你得传递足够的内存,也就是你不能事先知道这个函数到底要多大的BUFFER。另一种方法就是在函数内部申请static变量,当然这也是全局区的变量,但这种做法的缺点就是,当函数多次运行时,static变量里面的数据会被覆盖。这种类型的另一个方法就是使用全局变量,但这和使用static变量很相同,不同的是全局变量可以操作控制,而static变量如果不把它传出函数,就不可对它操作控制了。 另一类方法就是上面所述的,利用堆里的内存来实现,但存在危险,~_~。 至于其他的方法,目前还没想到。
相关阅读 更多 +