Thread: malloc() in function, free() without

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    9

    malloc() in function, free() without

    Hallo I have a question.
    Is that valid, or have I then a memory lack?
    Code:
    char *getArray(int n)
    {
      char *ptr = malloc(n);
      return ptr;
    }
    
    int main(void)
    {
      char *ptr = getArray(100);
      strcpy(ptr, "some stuff");
      free(ptr);
    
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Jul 2011
    Location
    Champaign, Illinois, United States
    Posts
    27
    That would be valid yes. If you are unsure you can use valgrind to see if you are infact leaking memory. In this case, you are not.

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    And the reason you are valid is because the library function malloc is used to allocate a block of memory on the heap.

  4. #4
    Registered User
    Join Date
    Aug 2012
    Posts
    9
    Thank you for quick answers.
    To breimer273: I have to see how valgrind works.
    To std10093: I had doubts, whether free() correct works if I allocate the memory in a separate block (in a function).

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    I figures that out,that's why i said that is been allocated into the heap.You successfully reserved a pointer (after the function terminated),so that you have access to what you allocated.That way you could access the heap and free the memory.If no pointer was reserved after the function was terminated,then you would be unable to free it,but the memory would remain allocated!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Create malloc and free function in C?
    By guestcheap in forum C Programming
    Replies: 47
    Last Post: 08-19-2011, 08:17 PM
  2. Malloc - Free giving double free or corruption error
    By andrew.bolster in forum C Programming
    Replies: 2
    Last Post: 11-02-2007, 06:22 AM
  3. malloc & free
    By akrlot in forum C Programming
    Replies: 1
    Last Post: 10-01-2007, 05:03 AM
  4. need help with malloc-free
    By sleith in forum C Programming
    Replies: 4
    Last Post: 08-22-2007, 08:07 PM
  5. Function to check memory left from malloc and free?
    By Lechx in forum C Programming
    Replies: 4
    Last Post: 04-24-2006, 05:45 AM