Haroon Shafiq wrote:
a wrote:
I would like to have a function to process an input integer and return the
result. The following code will generate a memory leak.
oh no it doesn't
How should I write this idea properly?
int func(int num){
//process the num, counting the loop
int result;
return result;
if you had returned a pointer to result then you would have a problem.
But C *copies* the return value, hence the fact that result has
disappeared after the funtion has exited doesn't matter.
}
main(){
int result;
result = func(7);
}
Try some thing like this.
/*CODE BEGINS*/
#include <stdio.h>
you forgot stdlib
int* func(int num){
//process the num, counting the loop
int *result;
result = malloc(sizeof (int));
//check for any error during allocation
//assuming this function will return a NULL in case of an error.
return result;
}
main(){
int *result;
result = func(7);
//perform some usual sanity checks here.
//_dont_ forget to free the allocated memroy here.
if (result != NULL){
free(result);
result = NULL;
}
}
/*CODE ENDS*/
this is just plain silly. Would you seriously malloc() a single
integer?
I'm sure we dream up situations where this might make sense but
normally it is just WRONG.
--
Nick Keighley
Let me get this straight: I'm going to run the Linux so I can run a
Java RTE so I can run a PDP emulator so I can run Unix V7 so I
can rebuild V6 from the Lions-commented source in a book legally
reprinted from an illegally photocopied Australian book based on
source code that came from New Jersey by way of Wales.
To quote Calvin and Hobbes, "The theological implications are
staggering."