-
Segmentation Fault?
I realize a segmentation fault occurs when trying to access restricted memory. However, I have no clue why this is happening. Here's my code. It's converting a decimal number to a binary number.
Code:
void tobinary(int x, char s[]);
int main() {
char hold[4];
tobinary(5, hold);
return 0;
}
void tobinary(int x, char s[]){
int k=0,n=0;
int neg=0;
int sLength=sizeof(s);
int remain;
int temp[sLength];
if (x<0) {
x=-x;
neg=1;
}
do {
remain=x%2;
x=x/2;
temp[k++]=remain+'0';
} while (x >0);
if(neg) {
temp[k++]='-';
}
else {
temp[k++]=' ';
}
while (k>=0) {
s[n++]=temp[--k];
}
s[n-1]=0;
k=0;
while (k<4) {
printf("%d", s[k]);
k++;
}
}
-
That bit there is going to cause some trouble for you. sizeof(s) gives you the size of a pointer on your machine. If you want the size of an array which is outside of the function, you will need to calculate the size and then pass that into the function as a parameter.
Read 6.1-6.4b here to get an idea of why this is so.
-
sizeof() only works on an array in the scope that the array was defined. You define your array in main() and then use sizeof() in a different function, which won't work. In this case it returns the size of a pointer (which is what it sees s as) instead of the size of the array you allocated in main().
You could pass a 3rd argument to tobinary() to tell it specifically how big to make your temp array.
-
I removed sizeof() and instead passed an integer, still get a segmentation fault
-