yulian
yulian

Reputation: 1627

App crashes while printing array after free()

Why does it crash while trying to printf() after having free()?

I've created dyanmic array. Displayed elements. Filled each elements with value. Then freed memory using free(). And then trying to display elements again.

Here is the code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int *p;

    p = (int *)malloc(10 * sizeof(int));

    for ( i = 0; i < 10; i++ )
        printf("%d  ", p[i]);
    printf("\n");

    for ( i = 0; i < 10; i++ )
        p[i] = i;

    for ( i = 0; i < 10; i++ )
        printf("%d ", p[i]);
    printf("\n");


    free(p);
    p = NULL;

    for ( i = 0; i < 10; i++ )  /* App crashes around here. */
        printf("%d ", p[i]);
    printf("\n");

    return 0;
}

P.S. I'm new to C.

Let me know what is wrong, please.

Upvotes: 0

Views: 134

Answers (3)

rr_ovi
rr_ovi

Reputation: 293

One thing always to be remembered.. A freed memory can return the expected result (it sometimes does). Me too sometimes suffered with the problem.. U can finde useful insight here:

Can a local variable's memory be accessed outside its scope?

Now come to your code:

free(p);

Here you may get your expected things..but u r not guaranteed and r not permitted to use this. It is undefined behaviour. But now

p = NULL;

is something that is crashing your program. Because the pointer now points to NULL, and it is not permitted to de-reference a NULL pointer. Do not point to NULL if you don't actually need it. And never ever de-reference a NULL pointer.

Upvotes: 1

Dipto
Dipto

Reputation: 2738

When you free any memory, its gone. You can not use it any more.

You should free the after you are done with it.

You are using the pointer p after you have freed it. The system assumes you do not need the memory once you free it. So it does not reserve it for you. It may work some times if the memory is still unused. But in this case you are assigning NULL to the pointer p and then trying to print the value present there, which is definitely not going to work.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409176

Because you reference memory pointing to NULL.

This is actually undefined behavior so it might work, but dereferencing a NULL pointer most likely will cause a crash.


Even if you don't set the pointer to NULL it's still undefined behavior to derreference unallocated memory, and although it most likely won't crash it's still a bad thing to do.

Upvotes: 4

Related Questions