[英]Why am I getting a segmentation fault 11?
I am getting a segmentation fault 11 on my printArr
function though I do not know the reason why. 尽管我不知道原因,但我的
printArr
函数出现了分段错误11。 My code compiles. 我的代码可以编译。 There is no segmentation fault if I do not include the
printArr
function. 如果不包含
printArr
函数,则不会出现分段错误。 Any help will be greatly appreciated. 任何帮助将不胜感激。
void printArr(int* arr, int arrlen){
printf("{");
for(int i = 0; i < arrlen; i++){
printf("%d,", arr[i]);
}
printf("}\n");
}
int countDeLen (int* in, unsigned int inlen){
int counter = 0;
if (inlen % 2 == 1){
return -1;
}
if (inlen == 0){
return 0;
}
int i = 0;
while (i < inlen){
counter += in[i];
i += 2;
}
return counter;
}
void rle_decode(int* in, unsigned int inlen, int** out, unsigned int* outlen){
outlen[0] = countDeLen(in,inlen);
if(outlen[0] == -1){
fprintf(stderr, "the code must have an even length!!!\n");
exit(1);
}
int* outCode = (int*)malloc(outlen[0] * sizeof(int));
out = (int**)malloc(outlen[0] * sizeof(int));
if(outlen[0] == 0){
return;
}
int codeIndex = 0;
int i = 0;
while(i < inlen){
for(int a = 0; a < in[i]; a++){
outCode[codeIndex] = in[i+1];
codeIndex++;
}
i+=2;
}
out[0] = outCode;
return;
}
int main(int argc, char *argv[])
{
printf("testing rle_decode()\n");
int dtest1[] = {2,1,3,4,2,3}; unsigned int dlen1 = 6; int *out1; unsigned int outlen;
rle_decode(dtest1, dlen1, &out1, &outlen);
printArr(*out1,outlen);
}
I am getting a segmentation fault 11 on my printArr function though I do not know the reason why. 尽管我不知道原因,但我的printArr函数出现了分段错误11。 My code compiles.
我的代码可以编译。 There is no segmentation fault if I do not include the printArr function.
如果不包含printArr函数,则不会出现分段错误。 Any help will be greatly appreciated.
任何帮助将不胜感激。
You're not calling printArr()
correctly. 您没有正确调用
printArr()
。 It should be: 它应该是:
printArr(out1,outlen);
Your code is equivalent to calling 您的代码相当于调用
printArr(out1[0], outlen);
But printArr()
requires the first argument to be a pointer to an array of int
, not a single int
. 但是
printArr()
要求第一个参数是一个指向int
数组的指针,而不是单个int
。
You should have gotten a warning about the mismatching types. 您应该已经收到有关类型不匹配的警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.