[C] freeing memory allocated in a function

From: Marlene Stebbins (stebbins_at_email.com)
Date: 05/31/04


Date: Sun, 30 May 2004 22:56:11 GMT

I'm using the code below to illustrate a situation that always
puzzles me when memory is allocated dynamically in a function.
There are two calls to malloc in the program, one in main() and
the other in polar2cart(), but only one call to free.

Have I correctly freed all dynamically allocated memory here? If
not, where should the memory allocated in the function be freed?

/* convert polar to Cartesian coordinates */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846
double* polar2cart(double r, double theta);

int main(int argc, char* argv[])
{
   double r, theta;
   double* xy;

   if(argc != 3)
   {
     fprintf(stderr, "enter radius and angle\n");
     exit(EXIT_FAILURE);
   }
   r = strtod(argv[1], NULL);
   theta = strtod(argv[2], NULL);
   xy = malloc(2 * sizeof(*xy));
   xy = polar2cart(r, theta);
   printf("\nx = %f y = %f\n", xy[0], xy[1]);
   free(xy);

   return 0;
}

double* polar2cart(double r, double theta)
{
   double cartx, carty, radians;
   double* cartxy;

   cartxy = malloc(2 * sizeof(*cartxy));
   radians = theta * (PI / 180.0);
   cartx = r * cos(radians);
   carty = r * sin(radians);
   cartxy[0] = cartx;
   cartxy[1] = carty;

   return cartxy;
}



Relevant Pages

  • Re: [C] freeing memory allocated in a function
    ... > puzzles me when memory is allocated dynamically in a function. ... Each 'malloc' should have a corresponding 'free'. ... to document the allocation so that the programmer will remember to ... > double* polar2cart(double r, double theta) ...
    (alt.comp.lang.learn.c-cpp)
  • Thank You -- Thomas J. Gritzan
    ... Thomas -- Your suggestion to malloc() out a block of memory was the ... Below are some details of my memory issues ... ... As a work around solution I guessed a ram disk would solve the ... persistence will frustrate the off topic police and give them a target ...
    (comp.lang.c)
  • Re: Simple question about headers and malloc!
    ... Therefore I am making all of its declarations ... memory (using malloc) and then exit back to main. ... allocation, I get data strored from the second allocation... ...
    (microsoft.public.vc.language)
  • Re: ten thousand small processes
    ... Stack needs to be executable for the current signal trampoline ... the use of malloc() that is causing your primary ... if there is any heap memory in use at all, no matter what you do, ... either directly, as a 4M page mapping (not used for user processes, ...
    (freebsd-performance)
  • Re: Help with Enter and Leave Instructions
    ... >>> for Memory Accesses, ... > The only standard way to do it is via malloc. ... Uh, SBRK/BRK is a standard, documented system call. ... > I really don't understand the objection to using C libraries. ...
    (alt.lang.asm)