为什么我的程序在将内存分配给双指针时产生seg-fault C

问题描述:

为什么此程序导致分段错误?我想要有一个动态分配内存的指针数组,以便我可以有一个字符串数组。为什么我的程序在将内存分配给双指针时产生seg-fault C

我搜索过类似的问题,如How to pass a double pointer to a function without segmentation fault C language

请解释为什么它赛格断层

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

void mem_alloc(char* p, char** dp); 

int entries = 0; 
int mem_allocated = 0; 

int main() { 

    char* p = "ksdfahj93qhf9"; 
    char* p1 = "siodfnrieopq"; 
    char* p2 = "erf9ih94gri9g"; 

    char** dp = NULL; 

    mem_alloc(p, dp); 
    mem_alloc(p1, dp); 
    mem_alloc(p2, dp); 

    for(int i = 0; i < entries; i++) { 

     printf("%s", dp[i]); 
    } 
} 
void mem_alloc(char *p, char** dp) { 
    if(entries == mem_allocated) 
     if(mem_allocated == 0) 
      mem_allocated = 3; 
    void** temp = realloc(dp, mem_allocated * (sizeof(p))); 
    if(!temp) 
     perror("Memory allocation failed!"); 

    dp = (char**) temp; 
    strcpy(dp[entries++], p); 

} 
+0

我看到一些乱糟糟的东西,而不是解引用什么应该是和解引用什么不应该... –

+0

在哪条线路上发生故障? – klutt

+0

你不能在函数内部更新调用方'dp'作为参数('char ** dp')。修复像[this](http://ideone.com/0Ft10C) – BLUEPIXY

在你mem_alloc功能修改功能参数dp。这个修改在函数之外是不可见的。结果,main中的dp从不更改,并且仍设置为NULL。

您需要将此变量的地址传递给该函数,然后在函数中取消引用该指针来更改它。

所以你函数变为:

void mem_alloc(char *p, char ***dp) { 
    if(entries == mem_allocated) 
     if(mem_allocated == 0) 
      mem_allocated = 3; 
    char **temp = realloc(*dp, mem_allocated * (sizeof(p))); 
    if(!temp) 
     perror("Memory allocation failed!"); 

    *dp = temp; 
    (*dp)[entries++] = strdup(p); // space also needs to be allocated for the new string 
} 

你这样称呼它:

mem_alloc(p, &dp); 
+0

而不是在函数中添加额外的星号,我会删除'main'中的星号...... –

+0

'void ** temp = ...'应该是'void * temp = ...'。这种方式可以在这里投射:'* dp =(char **)temp;'可以被删除。 – alk

+0

@alk实际上,使它成为'char **'更有意义,因为这就是它分配给它并删除了演员阵容。编辑。 – dbush

两个错误。首先是dbush提到的那个。

其次,在复制之前,您没有为您的字符串分配空间。您可以使用strndup()而不是strcpy()

+0

感谢您的帮助。我可以问,为什么我需要为字符串分配内存,如果'dp'变量已经为它分配了一个新的指针的内存?是否因为'mem_alloc'超出范围后'p'会被销毁?对不起,我是C新手。 –

+0

您正在为指针数组分配内存。然后您需要为阵列中的每个指针分配内存以保存要复制的字符串。 – Seth

+0

我很困惑,因为我习惯于将字符串文字赋值给char指针。但是现在,我必须在为指针数组分配内存之后为内存分配内存? –