Reputation: 71
I am getting a segmentation fault 11 on my printArr
function though I do not know the reason why. My code compiles. There is no segmentation fault if I do not include the printArr
function. 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. My code compiles. There is no segmentation fault if I do not include the printArr function. Any help will be greatly appreciated.
Upvotes: 0
Views: 48
Reputation: 781210
You're not calling printArr()
correctly. 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
.
You should have gotten a warning about the mismatching types.
Upvotes: 3