Динамический указатель на указатель в C «LeetCode», malloc перераспределяет бесплатно

#arrays #c #pointers #malloc #realloc

Вопрос:

я пытаюсь проникнуть в c, но я думаю, что не буду настолько хорош в НЕОЖИДАННОМ поведении или ошибке сегментации, я был в задаче решения вопроса given an array of signed integer like [-1,0,1,2,-1,-4] found all the unique triplet that sums to 0 , затем у меня есть шаблон для начала кодирования

int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) насколько я понимаю, я должен вернуть указатель на указатель int (если я его получил, это должен быть 2d-массив), то это было мое решение. Сначала я написал функцию, которая возвращала бы мне массив int следующим образом.

 int* triplet(int n1,int n2,int n3){
int* n = malloc(sizeof(int)*3);
n[0]=n1;
n[1]=n2;
n[2]=n3;

//printf("ngotHere %d %d %dn",n[0],n[1],n[2]);
//that works, triplet are right

return n;
}
 

затем я начал все вычисления, необходимые в 3 вложенных циклах, чтобы проверить каждое число только один раз и суммировать. Если сумма == 0, я могу добавить свой тройной массив в корневой массив, тот, который я должен вернуть.
Код выглядит следующим образом:

     int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){

int sizeCount=0;

//int** retArr = malloc(sizeof(int*));
int** retArr;

for(int a=0;a<numsSize-2;a  ){

for(int c= numsSize-1;c>a 1;c--){

for(int b=a 1;b<c;b  ){

if (nums[a] nums[b] nums[c]==0){

retArr =(int**) realloc(retArr,sizeof(int *) *   sizeCount);
retArr[sizeCount-1]=triplet(nums[a],nums[b],nums[c]);

//printf("ngotHere %d %d %dn",retArr[sizeCount-1][0],retArr[sizeCount-1][1],retArr[sizeCount-1][2]);

}}}}
*returnSize=sizeCount;

//**returnColumnSizes= sizeCount;
returnColumnSizes=realloc(returnColumnSizes,sizeof(int *)*sizeCount);
for (int i =0 ;i < sizeCount;i  ){
    returnColumnSizes[i] = malloc(sizeof(int));
    returnColumnSizes[i][0]=3;
}
//printf("n%dn",returnColumnSizes[1][0]);
return retArr;

}
 

я также не могу понять параметр функции;
threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
нумс-это массив, который я должен проверить, numSize должна быть длина, тип int* returnSize должен быть размер возвращаемого массива в указатель, как если бы я нашел 2 тройни, то должно быть 2, инт** returnColumnSizes я надеюсь, что должен содержать тройни размер, в моем случае, очевидно, должно быть 3,
я попытался разыменовать и установите значение 3, но это дало мне ошибку **returnColumnSizes = 3; дает мне все то ошибка и предупреждение.
поэтому я подумал, что должен был объявить 2d массив, содержащий 3 в позиции 0 для каждой найденной тройки, поэтому в итоге написал эту процедуру

 returnColumnSizes=realloc(returnColumnSizes,sizeof(int *)*sizeCount);
for (int i =0 ;i < sizeCount;i  ){
    returnColumnSizes[i] = malloc(sizeof(int));
    returnColumnSizes[i][0]=3;
}
 

after one night lost i still get segmentation fault and bad call to free or malloc,
the exercise say that i must not care about freeing couse the tests will do for me.

i also wrote a study case to better understand what appens, and thats the main function i ended up with.

 int main()
{
    int nums[6] = {-1,0,1,2,-1,-4};
    int* returnSize = malloc(sizeof(int));
    int** returnColumnSizes = malloc(sizeof(int *));
    int** ret = threeSum(nums, 6, returnSize,  returnColumnSizes);
    for(int i=0;i<*returnSize ;i  ){
        printf("ntriplet %d: %d %d %dn",i,ret[i][0],ret[i][1],ret[i][2]);
    }
    printf("Hello World");

    return 0;
}
 

do i misunderstood someting really necessary to get malloc and pointer right or i just wroting useless code different from what asked?
i can’t debug more couse the compiler start going crazy with overflow error or bad pointer called in __lib etc.etc. malloc internal
realloc(): invalid pointer: 0x00007fdfff72bae0 ***
ithink that error is gotten from the returnColumnSizes that i mess, but i can’t get that work in any way… some of you guys can point me up in the right direction? does someone know some good resources that will explain me those concept better via example, you of a better view sight of mine, do u scrute someting really bad in my code? and how do you recognize it?