C-使用双指针分配动态内存 [英] C - dynamic memory allocation using double pointer

查看:113
本文介绍了C-使用双指针分配动态内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在函数名称myalloc()中分配一些内存,并在main()中使用并释放它. 我正在使用双指针来执行此操作,这是可以正常工作的代码,

I am allocating some memory in a function name myalloc() and using and freeing it in main(). I am using double pointer to do this, here is the code which works fine,

//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;
}

但是下面的代码不起作用,并给出了分段错误. 我认为这是使用双指针的另一种方式.

But following code does not work and gives segmentation fault. I think this is another way to use double pointers.

//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;
}

请澄清一下,为什么在第二个示例中会给我段错误.

Please clarify me, why it is giving me seg fault in second example.

注意:语言= C,编译器= GCC 4.5.1,操作系统= Fedora Core 14

Note: Language = C, Compiler = GCC 4.5.1, OS = Fedora Core 14

此外,我知道已经有人问过与使用双指针分配内存有关的问题,但是它们不能解决此问题,因此请不要将其标记为重复性问题.

Also, i know that there are some question already been asked related to memory allocation using double pointers, but they don't address this issue, so please don't flag it as repetitive question.

推荐答案

char **ptr = 0;
*ptr = malloc(255);

尝试将malloc返回的指针写入ptr指向的地址(类型为char*).该地址原来是... 0,它不是可写内存.

tries to write the pointer returned by malloc to the address(of type char*) pointed to by ptr. The address turns out to be ... 0, which is not writable memory.

ptr应该指向您可以写入的地址.您可以执行以下操作之一:

ptr should point to an address you can write to. You can do one of the following:

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

这篇关于C-使用双指针分配动态内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆