GeeksforGeeks » C/C++ Programming Questions

A C malloc() and free() question

(4 posts)

Tags:

  1. gagan
    guest
    Posted 1 year ago #

    void f(int y)
    {
          struct s *ptr;
          ptr = malloc (sizeof (struct)+99*sizeof(int));
    }
    
    struct s
    {
        int i;
         float p;
    };
    

    when free (ptr) is executed, then what will happen?

  2. Venki
    Moderator
    Posted 1 year ago #

    The argument to malloc is size_t type. The expression "sizeof (struct)+99*sizeof(int)" returns a constant of size_t type. What ever may be the constant malloc allocates that much size, and free can freeup same when called.

    melloc return void*, hence can be easily assigned to ptr (structure pointer). It is up to the programming to face the consequences if used without proper memory allocation.

  3. mario
    Member
    Posted 1 year ago #

    I think the question is what happens when you free a ptr outside the function.
    Here ptr is local to function f() , so when you come out of that function ptr is dead, so you cant use or free that ptr.
    Pls correct me if I'm wrong.

  4. Venki
    Moderator
    Posted 1 year ago #

    It is what we call as memory leak. If we come out of function, the scope of ptr will be over. There will be no question of freeing ptr. I guess the question is on incorrect allocation of space and accessing it by structure 's' pointer.


Reply

You must log in to post.

RSS feed for this topic