Reputation: 1527
I keep getting a segmentation fault 11 when I call this function
void flexibleArray(int *array, int *length) {
int cnt = 0, number = 0;
while (number!=-1) {
printf("\nInsert the variable :"); scanf("%d", &number);
if (number!=-1){
cnt++;
array = realloc(array, cnt * sizeof(int));
array[cnt-1] = number;
}
}
*length = cnt;
}
as
int *array = NULL, arrayLength;
flexibleArray(array, &arrayLength);
It's a really simple function that I've always used and I don't get why is it giving me this error right now. I've been playing with it around to try to nail down the line that's giving me the problem, and I found out that taking off the *length = cnt;
line apparently doesn't give me the problem. Can I avoid the error keeping that line?
Thanks
CORRECT CODE:
int* flexibleArray(int *length) {
int *flexArray = NULL;
int cnt = 0, number = 0;
while (number!=-1) {
printf("\nInsert the variable :"); scanf("%d", &number);
if (number!=-1){
cnt++;
flexArray = realloc(flexArray, cnt * sizeof(int));
flexArray[cnt-1] = number;
}
}
*length = cnt;
return flexArray;
}
and in main()
int *array = NULL, arrayLength;
array = flexibleArray(&arrayLength);
Upvotes: 0
Views: 82
Reputation: 12742
as a pointer initialised to null, while arrayLength is just defined as int and not initialised
In that case you need to pass its reference to function.
flexibleArray(&array, &arrayLength);
And function will become
void flexibleArray(int **array, int *length) {
int cnt = 0, number = 0;
while (number!=-1) {
printf("\nInsert the variable :"); scanf("%d", &number);
if (number!=-1){
cnt++;
*array = realloc(*array, cnt * sizeof(int));
(*array)[cnt-1] = number;
}
}
*length = cnt;
}
Or
return new pointer from the function.
int *flexibleArray(int *array, int *length)
{
....
return array;
}
from main
array = flexibleArray(array, &arrayLength);
Upvotes: 6