c Language // free function related question.

Asked 1 years ago, Updated 1 years ago, 67 views

I'm implementing the stack as an array, but in the code below,

After copying in the main function, delivering the copied stack

If free is used, a compilation error does not appear, but if you run it, free is read, but it is not executed, so I ask you a question.

The pointer that receives the _st_ar input in the copy function is not free either ㅠ<

All variables in the main were declared inside the main.

int *copy(int *_st_ar, int nsize,  int *_t)
{
    int i;

     int* _copy_ar = (int*)malloc(sizeof(int)*(nsize*2));
    for(i=0;i<nsize;i++)
    _copy_ar[i] = _st_ar[i];

    if(_st_ar != NULL)
    free(_st_ar);
    _st_ar = NULL;

    return _copy_ar;
}

void del(int *_copy_ar)
{
    free(_copy_ar);
   _copy_ar = NULL;
}

int main()
{
    // ...
    printf("copy the stack array\n");
    new_array = copy(stack_array, nsize, &top);
    printStack(stack_array, nsize);
    printStack(new_array, nsize*2);
    printf("destroy stack array\n");
    del(new_array);
    printStack(new_array, nsize*2);

    return 0;
}

data-structure stack c

2022-09-22 20:00

1 Answers

An error occurred at runtime using memory released through del().

The code you wrote will normally release the memory.

Based on what you say, it seems that the criteria for judging that it will not be released is because the address of the pointer has not changed to NULL.

This is natural because the factor transfer is call by value in the function call process.

void del(int *_copy_ar) {
    free(_copy_ar);   
    _copy_ar = NULL;
}

If you do _copy_ar = NULL; here, NULL is stored in the _copy_ar variable, but not in the variable you entered when you called. This is because _copy_ar is a different variable from the variable used in the call.

Therefore, if you also want to change the variable used for the call to NULL,

void del(int**_copy_ar) {
    free(*_copy_ar);   
    *_copy_ar = NULL;
}

int main() {
    int* array = /* ... */;
    // ...
    del(&array);
    return 0;
}

You should use a double pointer as shown in .


2022-09-22 20:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.