[C] freeing memory allocated in a function
From: Marlene Stebbins (stebbins_at_email.com)
Date: 05/31/04
- Next message: Craig Bumpstead: "Re: Creating an Array of Strings in C , Sorry if multiple posts"
- Previous message: Rodney B. Elliott: "Creating an error message table"
- Next in thread: Arthur J. O'Dwyer: "Re: [C] freeing memory allocated in a function"
- Reply: Arthur J. O'Dwyer: "Re: [C] freeing memory allocated in a function"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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;
}
- Next message: Craig Bumpstead: "Re: Creating an Array of Strings in C , Sorry if multiple posts"
- Previous message: Rodney B. Elliott: "Creating an error message table"
- Next in thread: Arthur J. O'Dwyer: "Re: [C] freeing memory allocated in a function"
- Reply: Arthur J. O'Dwyer: "Re: [C] freeing memory allocated in a function"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|