man*_*nan 4 c pointers memory-leaks memory-management
我在函数名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;
}
Run Code Online (Sandbox Code Playgroud)
但是下面的代码不起作用并给出了分段错误.我认为这是使用双指针的另一种方法.
//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;
}
Run Code Online (Sandbox Code Playgroud)
请澄清一下,为什么它在第二个例子中给出了我的段错误.
注意:Language = C,Compiler = GCC 4.5.1,OS = Fedora Core 14
此外,我知道有一些问题已经被问及与使用双指针的内存分配有关,但它们没有解决这个问题,所以请不要将它标记为重复的问题.
phi*_*hag 10
char **ptr = 0;
*ptr = malloc(255);
Run Code Online (Sandbox Code Playgroud)
尝试将返回的指针写入ptr指向malloc的地址(类型char*).地址结果是...... 0,这是不可写的内存.
ptr应指向您可以写入的地址.您可以执行以下操作之一:
char *stackPtr; // Pointer on the stack, value irrelevant (gets overwritten)
ptr = &stackPtr;
// or
char **ptr = alloca(sizeof(char*)); // Equivalent to above
// or
char **ptr = malloc(sizeof(char*)); // Allocate memory on the heap
// note that ptr can be 0 if heap allocation fails
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13963 次 |
| 最近记录: |