【问题标题】:Why does my program produce seg-fault when assigning memory to a double pointer C为什么我的程序在将内存分配给双指针 C 时会产生 seg-fault
【发布时间】:2017-07-14 17:15:06
【问题描述】:

为什么这个程序会导致分段错误?我正在尝试拥有一个动态分配内存的指针数组,以便我可以拥有一个字符串数组。

我已经搜索过类似的问题,例如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);

}

【问题讨论】:

  • 我看到一些混乱,不取消引用应该是什么和取消引用不应该是什么......
  • 段错误发生在哪一行?
  • 你不能更新调用方dp内部函数作为参数(char **dp)。修复this
  • void** temp = ... 应该是void* temp = ...。

标签: c pointers dynamic-memory-allocation c-strings


【解决方案1】:

在您的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);

【讨论】:

  • 我不会在函数中添加额外的星号,而是删除main中的星号...
  • void** temp = ... 应该是 void* temp = ...。这样这里的演员表:*dp = (char**) temp; 可以被删除。
  • @alk 实际上,将其设为char ** 更有意义,因为这是分配给它并移除演员表的内容。已编辑。
【解决方案2】:

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

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

【讨论】:

  • 感谢您的帮助。请问,如果dp 变量已经为新指针分配了内存,为什么我需要为字符串分配内存?是因为一旦mem_alloc 超出范围,p 就会被销毁吗?抱歉,我是 C 新手。
  • 您首先为指针数组分配内存。然后你需要为数组中的每个指针分配内存来保存你正在复制的字符串。
  • 我很困惑,因为我习惯于将字符串文字分配给 char 指针。但是现在,给指针数组分配内存后还要给指针分配内存?
  • 您的字符串文字已经分配。因此,如果您想将该内存分配给分配的指针,您可以。但是您试图复制文字,这需要分配新的内存。
猜你喜欢
  • 1970-01-01
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
  • 2020-03-04
  • 2017-07-25
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
相关资源
最近更新 更多