【发布时间】:2011-06-09 05:56:29
【问题描述】:
我在函数名 myalloc() 中分配一些内存,并在 main() 中使用和释放它。 我正在使用双指针来执行此操作,这是可以正常工作的代码,
//Example # 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void myalloc( char ** ptr)
{
*ptr = malloc(255);
strcpy( *ptr, "Hello World");
}
int main()
{
char *ptr = 0;
myalloc( &ptr );
printf("String is %s\n", ptr);
free(ptr);
return 0;
}
但以下代码不起作用并给出分段错误。 我认为这是使用双指针的另一种方式。
//Example # 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void myalloc( char ** ptr)
{
*ptr = malloc(255);
strcpy( *ptr, "Hello World");
}
int main()
{
char **ptr = 0;
myalloc( ptr );
printf("String is %s\n", *ptr);
free(*ptr);
return 0;
}
请澄清一下,为什么它在第二个示例中给了我段错误。
注意:语言 = C,编译器 = GCC 4.5.1,操作系统 = Fedora Core 14
另外,我知道已经有人问过一些与使用双指针进行内存分配有关的问题,但他们没有解决这个问题,所以请不要将其标记为重复性问题。
【问题讨论】:
-
什么是 foo?它应该是 myalloc 吗?
-
在这两个例子中,我都忘了用 myalloc() 替换 foo().. 抱歉..
标签: c pointers memory-leaks memory-management