0

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

  • Free() doesn't clear the value there, it just de-allocates the memory, means the memory becomes free to be allocated to another program, but till that happens your data will be there. – PunyCode Dec 07 '19 at 03:08

1 Answers1

1

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.

foreverska
  • 585
  • 3
  • 20
  • 1
    While setting the pointer to NULL can be a good thing, it's important to remember that it may be other pointers pointing to the same memory. You are not freeing the pointer. You're freeing what it is pointing to. – klutt Dec 07 '19 at 00:54