Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
freeing memory
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Frank Silvermann, post: 2468852"] /* partition2.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define SWAP(m, n) (tmp = (m), (m) = (n), (n) = tmp) #define ITERATIONS 10 int rand_in_range(int, int); int * partition(int, int); int main(void) { int m=8, n=3, i; int *p; /* all declarations in main need to be north of here */ /* seed timer */ srand(time(NULL)); /* call partition and examine returns */ printf("set has %d elements and %d partitions\n", m, n); for(i = 0; i < ITERATIONS; i++) { p = malloc((n)*sizeof(int)); p = partition(m,n); printf("m in n chunks: %d %d %d\n", p[0], p[1], p[2]); /* free p; */ } return 0; } int rand_in_range(int m, int n) { /*seed srand in main */ /* [m, n] is range */ int roll_again_threshold, divisor, result, tmp, offset, num_results; if (m>n) SWAP(m, n); offset = m; num_results = n - m + 1; if (num_results == 1) { return m; } roll_again_threshold = RAND_MAX - RAND_MAX%num_results; divisor = roll_again_threshold/num_results; do { result = rand(); } while (result >= roll_again_threshold); result /= divisor; return offset + result; } int * partition(int m, int n) { int top_range, i, p; int *q; /* end declarations */ /* if n>m bomb out */ if (n > m) return NULL; top_range = m - n; q = malloc((n)*sizeof(int)); for (i=0; i<(n-1); i++) { p=rand_in_range(0, top_range); q[i] = p + 1; top_range = top_range - p; } q[n-1]=top_range + 1; return q; } /* end source */ I ask my compiler to carve out memory in main and in a subroutine. The adage is that if one asks an OS for memory, he must give it back. I would think that the requested memory in the subroutine would disappear when the return is made. It would also seem that I've created a memory leak in main, but when I add a free where it is now commented out, I get an error. Happy for any hints. frank[/i] [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
freeing memory
Top