I've been revisiting the C language and am having trouble freeing up memory after use in my program:
int tvalue = 2;
while (smult == 0) {
int * tvaluearray = calloc(allnum, sizeof(int));
tvaluearray = frequencyArray(tvalue, allnum, tvaluearray);
printf("tvalue = %d\n", tvalue);
//compare each index of the tvaluearray and the first array
for (int j = 0; j < allnum; j++) {
// printf("tvaluearray[%d]=%d >= firstarray[%d]=%d\n", j, tvaluearray[j], j, firstarray[j]);
if (tvaluearray[j] < firstarray[j]) {
// printf("Found the false statement\n");
break;
}
else if ( (j+1) == allnum ){
smult = 1;
// printf("Made it to else if! smult = %d\n", smult);
}
}
free(tvaluearray);
++tvalue;
}
The frequencyArray function is shown below:
int * frequencyArray (int target, int allnum, int targetarray[]) {
int divisor = 2;
for (int i = 0; i < allnum; i++)
targetarray[i] = 0;
//find the common factor frequency of the given number
while (target > 1) {
if (target % divisor == 0) {
targetarray[divisor] += 1;
target /= divisor;
}
else
++divisor;
}
return targetarray;
}
Having played around with this a bit, I've tried the following with different results:
1) removing the free of targetarray:
tvalue = 1306 --> segfault
2) including the free(targetarray):
tvalue = 29 free(): invalid next size (fast) Aborted (core dumped)
3) including free(targetarray) AND allocating 4*sizeof(int) for the tvaluearray calloc as opposed to just int:
tvalue = 31468 --> segfault
The third test had me changing the allocated space for the array with varying results before my program runs into the segmentation fault error. This has me thinking that there's an issue with the way I'm allocating space, but I think it just might be a little bit beyond my current understanding. Do any of y'all see where I may be going wrong?
tvaluearray = calloc(...)
directly followed bytvaluearray = frequencyArray(...)
... Is that last assignment really needed? DofrequencyArray
really need to return thetargetarray
argument? – Some programmer dudefrequencyArray
, what happens if thewhile
loop runs a little to far, makingdivisor
being out of bounds? – Some programmer dudefrequencyArray()
to the pointertvaluearray
. That pointer is tracking your allocated memory! It should only be read from, not written to. Look at it this way: if the functionfrequencyArray()
changes the value of the pointer, you're looking at undefined behavior (memory leak, crash, etc.). If it doesn't change the value, there's no point in returning anything. – Tim Randallallnum
infrequencyArray()
and in the calling code. The compiler will have no doubt which one is going to be referred to, but you might get confused. Specifically, note that if you change the value in the function, the value seen by the calling code won't change. – Tim Randall