Loop will not increment past 8? - c

I have a loop that involves a dynamically allocated array in C. For some reason it crashes after flag increments 7 times. This wasn't happening before I was reallocating the size of the array. Here is the code:
for (int i = 0; i < length-1; i++)
{
if (audio_samples[i] > threshold && run)
{
*event_flags = (int*)realloc(*event_flags, sizeof(int)*(flag+1)); // reallocate the size of the array
*event_flags[flag] = i;
// printf("FLAG CREATED! %i\n ", i);
printf("EVENT FLAG %i %i\n",flag, *event_flags[flag] );
if (flag >5) {
printf("%d\n", i);
}
flag++;
run = false;
}
Any ideas? Please keep in mind that the size of the array is indeed the same value as length. Here is an example of my errors:
EDIT 1
FILE ONE:
int *event_positions = (int *) malloc(1 * sizeof(int)); // let us start with 1 and then add more within the method. This should continue until we have all the flags we want.
int number_of_flags = event_extractor(vocal_data, size, event_positions);
FILE TWO:
float g_THRESHOLD_FACTOR = 2.3; // THIS INCREASES THE THRESHOLD VALUE.
int event_extractor (int *audio_samples, unsigned int size_of_audio ,int *event_flags)
{
int length = (int)size_of_audio;
// * * * * * * * * * * * * * * * * * *
// RECTIFY VALUES (MAKE ABSOLUTE) (MAKE ALL POSITIVE)
int *rectified_audio = (int *) malloc(length * sizeof(int)); // I took this line from wave header reader. The number is the number of samples of the hip hop track.
make_values_absolute(audio_samples, length, rectified_audio);
// If I convert to signed ints here would the method run more efficiently?
// * * * * * * * * * * * * * * * * * * * *
// LOW PASS FILTER
int *lopass_samples = (int *) malloc(length * sizeof(int)); // I took this line from wave header reader. The number is the number of samples of the hip hop track.
lopass(rectified_audio, length,0.5, lopass_samples);
int number_of_flags = apply_threshold (lopass_samples, length, &event_flags);
printf("\n\n\n NUMBER OF EVENTS AAAA --- %d\n", number_of_flags);
for (int i = 0; i < number_of_flags; i++) {
printf("FLAG %i -- %d \n", i, event_flags[i]);
}
return number_of_flags;
}
int apply_threshold (int *audio_samples, unsigned int size_of_audio, int **event_flags)
{
int flag = 0; // this will be the number of flags that I have
bool run = true; // this will make sure that a minimum amount of time passes before I grab another flag. It's a guard.
int counter = 0; // this is the counter for the above guard.
printf("\n\nCURRENT MINIMUM TIME: 20100 SAMPLES \n\n");
// event_flags[0] = 1; // this first one is a dud. within the loop we will automatically start adding flags
int threshold = calculate_threshold_value(audio_samples, size_of_audio);
printf("\n\n this is the threshold %d \n\n", threshold);
int length = (int)size_of_audio;
printf("LENGTH OF VOCAL AUDIO %d \n", length );
for (int i = 0; i < length-1; i++)
{
if (audio_samples[i] > threshold && run)
{
// ** is this realloc working ?
// event_flags = (int*)realloc(event_flags, sizeof(int) * (flag+1));
*event_flags = (int*)realloc(*event_flags, sizeof(int)*(flag+1)); // reallocate the size of the array
*event_flags[flag] = i;
// printf("FLAG CREATED! %i\n ", i);
printf("EVENT FLAG %i %i\n",flag, *event_flags[flag] );
if (flag >5) {
printf("%d\n", i);
}
flag++;
run = false;
}
if (!run) {
counter++;
if (counter > 20100) { // hardcode minimum size for now.
counter = 0;
run=true;
}
}
}
printf("\n\n\n NUMBER OF EVENTS --- %d\n", flag);
for (int i = 0; i < flag; i++) {
printf("FLAG %i -- %d\n", i, *event_flags[i]);
}
printf("\nFIVE samples before and after my second flag: \n 0 should indicate a reach in the threshold\n");
for (int i = 0; i <10 ; i++) {
printf("VOCAL SAMPLE %i %i \n", i-5,audio_samples[*event_flags[1]+i-5] );
}
return flag;
}

First you shouldn't cast the return of realloc.
Then if I suppose that the type of that variable is int*
*event_flags[flag] = i;
There is one * too much no?
Edit: After your remark on leaving out the cast.
So if your event_flags is effectively int**, you are really on the wrong track. Seeing your use, I would guess you simply want an array of int instead. If you do that and then
event_flags[flag] = i;
without * everywhere, your problem should go away.
If you really need that indirection, you'd have to allocate not only the array event_flags but also all the individual arrays these pointers are pointing to, with something like
for (size_t j = startvalue; j < something; ++j)
event_flags[j] = malloc(whatever);

I think you may have a problem with the precedence of the * operator versus the [] operator. That is *event_flags[flag] and (*event_flags)[flag] do not reference the same memory location. The first one correspond to **(event_flags + flag) (probably not accessible), while the second one correspond to *((*event_flags) + flag) (what you want).
So, you should rewrite your code to:
int** event_flags;
// ...
*event_flags = realloc(*event_flags, sizeof(int) * (flag + 1));
(*event_flags)[flag] = i;

Related

Free list of integers

I was trying to free a list of integers starting from the head and knowing how many elements are in the list, but I am getting an invalid pointer error.
The code is the following:
int* factors = job_factorization(number, size);
printf("Thread %d: job terminated. Result: ", params->thread_id);
int* tmp;
for (int i = 0; i < *size; i++){
printf("%d ", *factors);
tmp = factors;
factors++;
free(tmp);
}
int *job_factorization(int number, int *size) {
int *factors;
int array_size = SIZE_INCREASE;
int factor = 2;
if (number < 2)
return NULL;
factors = (int *) malloc(sizeof(int) * SIZE_INCREASE);
*size = 0;
while (number != 1) {
// check whether the number is divisible by the factor
if (number % factor == 0) {
// if there is no more space available, resize the array
if (*size == array_size) {
array_size += SIZE_INCREASE;
factors = (int *) realloc(factors, sizeof(int) * array_size);
}
// add the factor to the list of prime factors
factors[*size] = factor;
(*size)++;
number = number / factor;
}
else {
// if not a factor, move to the next prime number
factor = next_prime(factor);
}
}
return factors;
}
Does anyone have any idea of the reason why this is happening? I have no clue about it (the function job_factorization works correctly)
job_factorization makes one malloc (and a number of reallocs). To the user of job_factorization this looks like one allocation only and that only needs one free. Like this:
int* factors = job_factorization(number, size);
for (int i = 0; i < *size; i++) {
printf("%d ", factors[i]); // don't increase factors in the loop
}
free(factors); // one free
When you use realloc it replaces the old allocation, so if you first malloc for 1 element, then realloc for 2 elements, the result is one allocation with 2 elements - which requires one free only.

Segfault in C (during middle of for loops)

I'm trying to practice C by writing a memory-type card game. The game is compiled by gcc on ARMv8. The user enters a number "users_N" in the argument line and a board of cards is created size: 2N x 2N.
The program runs just fine when the number is 1 or 2. But if it's 3 or bigger, I get a segmentation fault when trying to initialize the board. I thought this meant it was a stack overflow, but I increased the stack size to unlimited on my SSH and the problem was not resolved. I don't think it's a problem with pointers or trying to access an array out-of-bounds either, as it runs just fine until after 10 cards are added to the array.
The print statements are just to determine exactly when the segfault occurs.See image of for loop segfault
EDIT: to add more context... I know it's a bit messy, sorry!
int main(int argc, char *argv[]) {
if (argc < 3){ //Checking user's command line input.
printf("Missing argument. Exiting... \n");
return 0;
}
users_N = atoi(argv[2]);
srand(time(NULL)); //Initialize random number generator.
int ***board = (int ***)malloc(2 * users_N * sizeof(int)); //Dynamic array to store the board values
for (int i = 0; i < 2 * users_N; i++){
board[i] = (int **)malloc(2 * users_N * sizeof(int)); /*Array of pointers (rows) filled with
an array (columns). */
for (int j = 0; j < 2 * users_N; j++){
board[i][j] = (int *)malloc(2 * sizeof(int)); //3rd dimension to show/hide cards.
}
}
initialize(board);
}
/*
* Function initialize sets up the board. It takes the 3D board array. A card deck is created the
* size of 2N^2, then shuffled and added to the board. The 3rd dimension is initialized
* completely to 1, so all cards are shown. There is no return.
*/
void initialize(int*** board){
int* cards = (int *)malloc(2 * users_N * users_N * sizeof(int)); //Create an array of cards.
printf("Cards created\n");
for (int c = 0; c < (2 * users_N * users_N); c++){
printf("card: %d\n",c);
cards[c]=c;
}
int half = 0;
while (half < 2){ //Divide up into 2 halves of the board, to repeat shuffle and card placement.
shuffle(cards);
int cardsNum = 0;
for (int j = 0; j < users_N; j++){ //For each row in the current half:
printf("\n row = %d ", j);
for (int k = 0; k < (users_N * 2); k++){ //For each column:
printf("col = %d ",k);
board[j + (half * users_N)][k][0] = cards[cardsNum]; /* Assign appropriate
card to each board
position. */
printf("set to: %d ", board[j + (half * users_N)][k][0]);
board[j + (half * users_N)][k][1] = 1;
cardsNum++;
printf("Card num: %d \n", cardsNum);
}
}
half++; //Moves to next half to repeat.
}
}
/*
* Function shuffle takes the array of cards as a parameter. It will then randomly mix array.
* Numbers are not repeated and will not exceed 2N*N-1. No return values.
*/
void shuffle(int *cards){
int j;
for (int k = 0; k < (2 * users_N * users_N) - 2; k++){
j = randomNum(k, (2 * users_N * users_N) - 1); //Assign a random number between k and 2N*N-1.
swap(cards, k, j);
printf("cards swapped: %d,%d\n",k,j);
}
}
/*
* Function swap takes the array of cards, two index integers. The index integers indicate the positions of
* the elements (cards) to switch. No return values.
*/
void swap(int *cards, int i, int j){
int temp = cards[i]; //Value of position i stored in temp.
cards[i] = cards[j]; //value of card j assigned to card i.
cards[j] = temp; //Value of temp assigned to card j.
}
Allocation of your board is wrong:
int ***board = (int ***)malloc(2 * users_N * sizeof(int));
^^^^^^^^^^^
wrong size
for (int i = 0; i < 2 * users_N; i++){
board[i] = (int **)malloc(2 * users_N * sizeof(int));
^^^^^^^^^^^
wrong size
...
}
When you have board as int *** you don't want size of int during first allocation. You want size of int **. Like
int ***board = malloc(2 * users_N * sizeof(int**));
A better approach is to use the variable name - like:
int ***board = malloc(2 * users_N * sizeof *board);
^^^^^^
Better approach
to get correct size
The same applies to the next malloc

Stuck in a for loop entering values to an array in C language

I am trying to practice with C by making a bubble sort program. The problem until now seems to be that the for loop that is giving values to the cells of the array is stuck after the condition is no longer fulfilled but it doesn't seem to be executing the commands in the loop. I don't know what is happening exactly and I have added some extra lines to see what is happening an these were my conclusions. Here is the code:
#include <stdio.h>
#include <stdlib.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int *sort(int *array)
{
int finish = 1;
while (finish = 1)
{
finish = 0;
for (int i = 0; i <= sizeof(array); i++)
{
if ((array + i) > (array + i + 1))
{
swap(array + i, array + i + 1);
finish = 1;
}
}
}
return array;
}
int main()
{
int s, res;
printf("Give me the size of the array being sorted(larger than 1) : ");
do
{
res = scanf("%d", &s);
if (res != 1)
{
printf("Wrong Input!\n");
exit(1);
}
if (s < 2)
printf("Only numbers equal or larger than 2\n");
} while (s < 2);
int array[s];
for (int i = 0; i < s; i += 1)
{
scanf("%d", array + i);
printf("%d %d %d\n\n", *(array + i), i, i < s); // I used this to check if my values were ok
}
printf("end of reading the array"); //I added this line to see if I would exit the for loop. I am not seeing this message
sort(array);
printf("\n");
for (int i = 0; i < sizeof(array); i++)
printf("%d\n\n", array + i);
printf("Array has been sorted! Have a nice day!\n\n************************************************************");
return 0;
}
See the annotations in the code:
#include <stddef.h> // size_t 1)
#include <stdio.h>
#include <stdlib.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int *sort(int *array, size_t size) // needs an extra parameter to know the size of the array
{
int finish = 1;
while (finish /* = 1 * you don't want assignment, you want comparison: */ == 1)
{
finish = 0;
for (int i = 0; i /* <= sizeof(array) */ < size - 1; i++) // i should be of type size_t
{
// if ((array + i) > (array + i + 1)) you are not dereferencing:
if(array[i] > array[i + 1])
{
// swap(array + i, array + i + 1); // easier to read imho:
swap(&array[i], &array[i + 1]);
finish = 1;
}
}
}
return array; // why does this function return anything? it is never used.
}
int main()
{
int s; /* , res; no need for an extra variable res */
printf("Give me the size of the array being sorted(larger than 1) : ");
do
{
// res = scanf("%d", &s);
// if (res != 1)
if (scanf("%d", &s) != 1)
{
printf("Wrong Input!\n");
// exit(1); // should be EXIT_FAILURE. Use return instead of exit() when in main().
return EXIT_FAILURE;
}
if (s < 2)
printf("Only numbers equal or larger than 2\n");
} while (s < 2);
int array[s];
for (int i = 0; i < s; /* i += 1* idiomatic: */ ++i) // size_t would be the correct type for s and i.
{
scanf("%d", /* array + i use indexes: */ &array[i]);
printf("%d %d %d\n\n", array[i], i, i < s); // again: indexes. i < s is allready ensured by the condition of the for-loop
}
printf("end of reading the array");
// sort(array); // sort will have no idea about the size of array use
sort(array, s); // instead.
printf("\n");
for (int i = 0; i < /* sizeof(array) 2) */ s; i++)
printf("%d\n\n", /* array + i * again you don't dereference */ array[i]);
printf("Array has been sorted! Have a nice day!\n\n************************************************************");
return 0;
}
1) size_t is the type that is guaranteed to be big enough to hold all sizes of objects in memory and indexes into them. The conversion specifier for scanf() is "%zu".
2) sizeof(array) in main() will yield the number of bytes in array, but you want the number of elements so you'd have to use sizeof(array) / sizeof(*array). But thats not needed since you already know its size. It is s.
This line
printf("end of reading the array");
has no line feed at the end of the string. This is a problem because printf is part of the family of functions called "buffered IO". The C library maintains a buffer of the things you want to print and only sends them to the terminal if the buffer gets full or it encounters \n in the stream of characters. You will not see, end of reading the array on your screen until after you have printed a line feed. You only do this after calling sort(). So all you know is your program is getting into an infinite loop at some point before the end of sort.
So there are actually three loops that could be infinite: the for loop you identified, the while loop in sort and the for loop inside the while loop. As the other answers point out, you have made the classic mistake of using assignment in the while conditional
while (finish = 1)
// ^ not enough equals signs
Unless your C compiler is really old, it is probably outputting a warning on that line. You should heed warnings.
Also, you should learn to use a debugger sooner rather than later. Believe me, it will save you a lot of time finding bugs.
In the sort function sizeof(array) returns the size of the pointer. (you can check it by yourself using printf("%d", sizeof(array).
The solution is to change your function to:
int sort(int* array, size_t size) { ... }
and call it with the correct array size:
sort(array, s);

Exporting print statements to external file

So I'm trying to teach myself , and Ive been doing online lab exercises to learn it. I wrote a program that goes into pretty good detail of arrays and structures. It uses random numbers to monitor for a spike of 100 psi, and then prints that as a 0 point, and prints the previous 10 seconds of the array and the next 10, as if I was collecting data. The next part of this exercise is to take the program's print statement, and have it write to an external file and have it print there. My thought process is to populate an array in the printout function that holds the values read from the file and then print from the array to screen. But I'm not sure how this would look, or really how to accomplish it. If anyone could point me in the right direction or give a good explanation it would be greatly appreciated!
My code so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define MAX_CHANGE 100
#define ARRAY_SIZE 21
typedef struct data_slice
{
int t; // -> Time
float tp; // -> Valve pressure
float tf; // -> Sodium flow
float tt; // -> Sodium temp in Celsius
} data_slice;
// Function Declarations
void get_values(float * pressure, float * flow, float * temp);
void printIt(data_slice * data);
void initializeArray(data_slice * data);
bool spikeValueRecorded(data_slice * data, int outputIndex);
int main()
{
srand((unsigned int)time(NULL));
data_slice data[ARRAY_SIZE];
int index = -1;
while (1)
{
// Initialize the entire array
initializeArray(data);
// If there's a spike.....
if (spikeValueRecorded(data, index))
{
// Set the previous "time" in array to negatives
int temp = index;
for (int i = 0; i >= -10; --i)
{
data[temp].t = i;
temp = temp - 1;
if (temp < 0)
temp = temp + ARRAY_SIZE;
}
// Record for 10 more seconds
for (int i = 0; i <= 10; ++i)
{
data[index].t = i;
index = (index + 1) % ARRAY_SIZE; // Increment the index of the circular array
get_values(&data[index].tp, &data[index].tf, &data[index].tt); // "Record" the values
}
break;
}
}
// Print the finished recording
printIt(data);
}
// Return: void
// in - Values of the data_slice struct
//
// Description: The three values of the struct (data_slice) to be filled in
void get_values(float * pressure, float * flow, float * temp)
{
*pressure = (float)(rand() % (700 - 500 + 1) + 500); // Range: 500 - 700
*flow = (float)(rand() % (20 - 10 + 1) + 10); // Range: 10 - 20
*temp = (float)(rand() % (200 - 100 + 1) + 100); // Range: 100 - 200
}
// Return: void
// in - The array of data_slice
//
// Description: Prints the entire array being passed in
void printIt(data_slice * data)
{
// Find the indice holding the time value of -10
int indice = 0;
for (int i = 0; i < ARRAY_SIZE; ++i)
{
if (data[i].t == -10)
{
indice = i;
break;
}
}
for (int i = 0; i < ARRAY_SIZE; ++i)
{
printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp, data[indice].tf, data[indice].tt);
indice = (indice + 1) % ARRAY_SIZE;
}
}
// Return: void
// in - The array of data_slice
//
// Description: Initializes the entire array to random values and their times to 0
void initializeArray(data_slice * data)
{
for (int i = 0; i < ARRAY_SIZE; ++i)
{
data[i].t = 0;
get_values(&data[i].tp, &data[i].tf, &data[i].tt);
}
}
// Return: boolean
// in - The array of data_slice
// out - Indice of the pressure spike
//
// Description: Returns true if a positive spike in pressure has been recorded.
// outputIndex will hold the 0-indice of the pressure spike, else -1
bool spikeValueRecorded(data_slice * data, int outputIndex)
{
float oldValue = data[0].tp;
for (int i = 0; i < ARRAY_SIZE; ++i)
{
if (data[i].tp - oldValue < MAX_CHANGE)
{
outputIndex = i;
return true;
}
}
outputIndex = -1;
return false;
}
You can use the fprintf call exactly like the printf call, with one difference. The first argument will be a pointer to a file handle (FILE*) which you create using a call to fopen("full or relative path","w").
The string format is now the second argument and the variable args list starts at arg 3
This is way you can write to file by using libc API
void printIt(data_slice * data)
{
// Find the indice holding the time value of -10
int indice = 0;
for (int i = 0; i < ARRAY_SIZE; ++i)
{
if (data[i].t == -10)
{
indice = i;
break;
}
}
//write to file
FILE *fp = fopen("output.txt", "wb"); //Binary mode since the size of array is fixed.
fwrite(data, sizeof(char), sizeof(data), fp);
fclose(fp);
for (int i = 0; i < ARRAY_SIZE; ++i)
{
printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp, data[indice].tf, data[indice].tt);
indice = (indice + 1) % ARRAY_SIZE;
}
}

Manipulating a global array in a recursive function

I'm working through an algorithms MOOC and have a small program that takes an array A of ints in arbitrary order, counts the number of inversions (an inversion being the number of pairs (i,j) of array indices with i<j and A[i] > A[j]).
Below is the code I've written. I'm trying to tackle it using a "divide and conquer" approach where we recursively split the input array into two halves, sort each half individually while counting the inversions and then merge the two halves.
The trick is I need to keep track of the number of inversions and sort the arrays, so I pass the original array around the various recursive calls as an argument to the function and pass the count of inversions as a return value.
The code executes correctly through the first set of recursive calls that successively divide and sort [1,5,3], however when I get to the 3rd invocation of mergeAndCountSplitInv it crashes at the line:
sortedArrayLeft = realloc(sortedArrayLeft, sizeof(int)*(rightLen + leftLen));
with the error:
malloc: *** error for object 0x100103abc: pointer being realloc'd was not allocated
I can't see where I'm not using malloc correctly and I've combed through this checking to see I'm doing the pointer arithmetic correctly and can't spot any errors, but clearly error(s) exist.
Any help is appreciated.
// main.c
// inversionInC
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// function to help with debugging array/pointer arithmetic
void logArrayLenAndContents (char *arrayName, int arrayToPrint[], int arrayLen){
printf("%s\n", arrayName);
printf("len:%d\n", arrayLen);
for (int idx = 0; idx < arrayLen; idx++) {
printf("array[%d]: %d\n", idx, arrayToPrint[idx]);
}
}
int mergeAndCountSplitInv(int sortedArrayLeft[], int leftLen, int sortedArrayRight[], int rightLen)
{
printf("Calling mergeAndCount with sortedArrayLeft:\n");
logArrayLenAndContents("left Array", sortedArrayLeft, leftLen);
printf("...and sortedArrayRight:\n");
logArrayLenAndContents("right Array", sortedArrayRight, rightLen);
int i = 0;
int j = 0;
int k = 0;
int v = 0; // num of split inversions
int* outArray;
outArray = malloc((leftLen + rightLen) * sizeof(int));
while (i < leftLen && j < rightLen) {
if (sortedArrayLeft[i] < sortedArrayRight[j]) {
outArray[k] = sortedArrayLeft[i];
i++;
} else{
outArray[k] = sortedArrayRight[j];
v += leftLen - i;
j++;
}
k++;
}
// if at the end of either array then append the remaining elements
if (i < leftLen) {
while (i < leftLen) {
outArray[k] = sortedArrayLeft[i];
i++;
k++;
}
}
if (j < rightLen) {
while (j < rightLen) {
outArray[k] = sortedArrayRight[j];
j++;
k++;
}
}
printf("Wrapping up mergeAndCount where outArray contains:\n");
logArrayLenAndContents("outArray", outArray, k);
sortedArrayLeft = realloc(sortedArrayLeft, sizeof(int)*(rightLen + leftLen));
return v;
}
int sortAndCount(int inArray[], int inLen){
printf("Calling sortAndCount with:\n");
logArrayLenAndContents("inArray", inArray, inLen);
if (inLen < 2) {
return 0;
}
int inArrayLenPart1 = ceil(inLen/2.0);
int inArrayLenPart2 = inLen - inArrayLenPart1;
int* rightArray = malloc(sizeof(int) * inArrayLenPart2);
rightArray = &inArray[inArrayLenPart1];
int x = sortAndCount(inArray, inArrayLenPart1);
printf("sortAndCount returned x = %d\n\n", x);
int y = sortAndCount(rightArray, inArrayLenPart2);
printf("sortAndCount returned y = %d\n\n", y);
int z = mergeAndCountSplitInv(inArray, inArrayLenPart1, rightArray, inArrayLenPart2);
printf("mergeAndCount returned z = %d\n", z);
return x+y+z;
}
int main(int argc, const char * argv[])
{
static int* testArray;
testArray = malloc(5 * sizeof(int));
for (int i = 0; i<=4; i++) {
testArray[0] = 1;
testArray[1] = 5;
testArray[2] = 3;
testArray[3] = 2;
testArray[4] = 4;
}
int x = sortAndCount(testArray, 5);
printf("x = %d\n", x);
return 0;
}
This happens because the value of sortedArrayLeft gets lost as soon as the function returns. The realocated value does not make it to the caller, so inArray of the sortAndCount may be pointing to freed memory if realloc needs to reallocate and copy.
In order to fix this, pass a pointer to the pointer, letting sortedArrayLeft to propagate back to inArray of sortAndCount:
int mergeAndCountSplitInv(int **sortedArrayLeft, int leftLen, int sortedArrayRight[], int rightLen) {
...
*sortedArrayLeft = realloc(*sortedArrayLeft, sizeof(int)*(rightLen + leftLen));
return v;
}
...
int sortAndCount(int **inArray, int inLen) {
...
int z = mergeAndCountSplitInv(inArray, inArrayLenPart1, rightArray, inArrayLenPart2);
}
...
int x = sortAndCount(&testArray, 5);

Resources