Search code examples
cmemory-managementmallocdynamic-memory-allocationfree

Function free() doesn't de-allocate memory from a vector


Why can I use the same vector even after I've used free(a) to de-allocate memory from it? By that, I mean that I can still operate with the same vector after freeing it from memory.

Is it a feature of malloc() or is it a bug in my code?

int main() {
    int n,i,j;
    int *a;

    printf("n = ");
    scanf("%d", &n);
    if((a=(int*)malloc((1+n)*n/2* sizeof(int)))==NULL){
        printf("Insuficient memory\n");
        exit(EXIT_FAILURE);
    }
    for(i=0;i<n;i++){
        for(j=0;j<n-i;j++){
            if(i==0 || j==0){
                *(a+(2*n-i+1)*i/2+j)=1;
            } else {
                *(a+(2*n-i+1)*i/2+j)=*(a+(2*n-i+2)*(i-1)/2+j)+*(a+(2*n-i+1)*i/2+j-1);
            }

        }
    }
    for(i=0;i<n;i++){
        printf("\n");
        for(j=0;j<n-i;j++){
            printf("%d ",*(a+(2*n-i+1)*i/2+j));
        }
    }
    free(a);
    printf("\nfree() has been used\n");
    for(i=0;i<n;i++){
        printf("\n");
        for(j=0;j<n-i;j++){
            printf("%d ",*(a+(2*n-i+1)*i/2+j));
        }
    }
    return 0;
}

Thanks in advance <3


Solution

  • This is a use-after-free and is undefined behavior. No one can guarantee what will or won't work.

    It's not a bug you can still access it. All free does is tell the system to release the memory. On average it will probably continue to be accessible for awhile. It is generally held that you should set a pointer to NULL after free so you do not accidentally use it after it has been freed.