The segmentation error occurs in this function:
#include <stdio.h>
#include <stdlib.h>
int heap [999],heap2 [999];
int* addDigit(int *arr, int SIZE, int D) {
int con=0;
for (int i = 0; i < SIZE; i )
con = con * 10 arr[i];
con = D;
int p = 0;
while (con >= 0) {
heap[p] = con % 10;
con /= 10;
p ;
}
for (int i = 0; i < p; i )
printf("%d ", heap[i]);
heap2[0] = 11;
heap2[1] = -1;
int *pp = heap2;
return pp;
}
This is main function:
int main() {
int N, digit;
scanf("%d", &N);
int arr[N];
for (int index = 0; index < N; index ) {
scanf("%d", &arr[index]);
}
scanf("%d", &digit);
int *ptr = addDigit(arr, N, digit);
int index = 0;
while (*(ptr index) !=-1) {
printf("%d", ptr[index]);
index ;
}
return 0;
}
Why am I getting a segmentation fault here?
This program gets input of array like [1 2 3]
and value k
, say 3;
it should print 1 2 6
.
I used two globally declared arrays here.
CodePudding user response:
Generally, the quickest way to locate the sources of segmentation faults, is the compile the program with the -g
flag to include debug information in the executable, and then to run the program using Valgrind.
In this case, the segmentation fault occurs in the reading of heap
here:
while (con >= 0)
{
heap[p] = con % 10;
con /= 10;
p ;
}
The variable con
will eventually become 0
and will stay at 0
due to the repeated division by 10. It will not become negative, and thus the while-loop will repeat infinitely. The index p
will increase until the program will try to access element 999 of heap
- which is out of bounds, i.e. this is a segmentation fault.
Perhaps you meant to write while (con > 0)
? This stop the loop when con
is zero (instead of negative, as before). Or perhaps you need a different solution, depending on what the intended functionality of the code is exactly.
PS. The segmentation fault does not happen "in the compiler", it occurs while the program is executed.