#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int debug = 1;
void copy_array(char* input, char** output, int len) {
*output = (char *)malloc(len * sizeof(*output));
if (debug) printf("copy_array: len: %x\n", len);
for (int i=0; i<len; i++) {
printf("Pre assignment: %x\n", input[i]);
*output[i] = input[i];
printf("Post assignment\n");
}
}
int main(void) {
char input[] = { 49, 27, 0x6d, 20, 0 };
char c;
char* output;
int len = strlen(input);
copy_array(input, &output, len);
return 0;
}
是示例代码,由于我不明白“*output[i] =...”行的原因,我遇到了段错误。
有人明白我做错了什么吗?
编辑:解决现有评论:
- 缺少 stdlib.h 包含
- 非空终止数组
- 不使用 sizeof 进行 malloc
编辑 2:Antti Haapala 解决了该问题:[] 比 * 结合得更紧密,因此需要“(*output)[i]”。
最佳答案
input
不是以 0 结尾的。对它调用 strlen
是未定义的行为。
您也没有分配足够的内存。您需要len * sizeof output[0]
。
关于c - 复制到 malloced 内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53969286/