【发布时间】: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