0

How to free memory allocated, I tried free(ptr), but it doesn't work as I accepted it do .

what are alternatives if I'm wrong? why is this behavior in my code?

typedef struct a
{
    int a;
    int b;
} aa;

aa* ptr = NULL;

int main()
{
    //code
    int input = 2;
    ptr = malloc(sizeof(aa)*input);

    for (int i = 0; i < input; i++)
    {
        ptr[i].a = 10;
        ptr[i].b = 20;
    }


    for (int i = 0; i < input; i++)
    {
        printf("%d  %d\n", ptr[i].a, ptr[i].b);
    }

    free(ptr);
    for (int i = 0; i < input; i++)
    {
        printf("%d  %d\n", ptr[i].a, ptr[i].b);
    }

    return 0;
}

Output:

10  20
10  20
After free 
 0  0
 10  20

what I'm accepting

Output:

10  20
10  20
After free 
 0  0
 0  0
machine_1
  • 4,266
  • 2
  • 21
  • 42
bbcbbc1
  • 95
  • 7
  • 4
    Accessing freed memory is UB.So you cannot expect anything. – Gaurav Sehgal Feb 16 '18 at 09:08
  • 3
    Accessing `ptr` after `free(ptr)` is [undefined behaviour](https://en.wikipedia.org/wiki/Undefined_behavior). – axiac Feb 16 '18 at 09:09
  • so why do i get output as 0 0 10 20 ,even after free? – bbcbbc1 Feb 16 '18 at 09:10
  • 4
    @bbcbbc1 because it's __undefined behaviour__, so anything can happen. – Jabberwocky Feb 16 '18 at 09:11
  • 5
    You rented an apartment. You ended your lease but kept a copy of the keys. The keys still work after your lease ended. A new tenant may or may not have moved in. It's not the landlords fault that you're trespassing. – Art Feb 16 '18 at 09:11
  • Any output is valid. The required behaviour is undefined. Your program could crash. It could reformat your hard drive. Both are fine. It is pointless to speculate! – Jonathan Leffler Feb 16 '18 at 09:12
  • Suggested reading: most upvoted answer of this question: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794 – Jabberwocky Feb 16 '18 at 09:12
  • Don't uses printf, it's shity function for memory, use write ! – Sigdev Feb 16 '18 at 10:25
  • @Aurélien could you elaborate? – Jabberwocky Feb 16 '18 at 10:35
  • And free() didn't set memory to 0, https://linux.die.net/man/3/free Use memset() for that http://www.cplusplus.com/reference/cstring/memset/ – Sigdev Feb 16 '18 at 11:20

0 Answers0