
question, malloc in a function
Quote:
>Hey all-
>If I allocate space to a local variable with malloc() in a function,
Be clear that you are talking about 2 objects/varioables here. Firstly
there is the pointer which may or may not be a local variable, and secondly
there is the object you created with malloc which is *not* a local
variable.
Quote:
>and return() from the function without free() -ing the malloc() -ed memory,
>does the memory return to the heap as the variable passes out of scope?
If you have an automatic (local) pointer that is destroyed when it
passes out of scope. The malloc'd variable itself has no scope since it
has no identifier/name. It has a 'duration' i.e. it lasts until it is
freed. If you destroy the pointer without first freeing the malloc'd
variable it remians allocated but you have no way of getting at it. This is
called a memory leak.
Quote:
>For example:
>#include<stdio.h>
>#include<string.h>
>char *substr(char *, int, int);
>main(int argc, char *argv[])
>{
>char thing[]="abcdefg";
>printf("\n%s",substr(thing,1,3));
>}
>char *substr(char *source, int start, int length)
>{
>char *dest;
>dest=malloc((length+1)*sizeof(char));
>strcpy(dest, "");
This strcpy is redundant. If it was needed it would be better to write
it as:
dest[0] = '\0';
Quote:
>strncpy(dest,&source[start-1],length);
>dest[length]='\0';
Consider replacing these three lines with:
dest[0] = '\0';
strncat(dest,&source[start-1],length);
Quote:
>return(dest);
>}
>The above code returns a substring of a given string. It works, I am just
>wondering whether overuse will do bad things.
If you call substr repeatedly without freeing the variable that malloc
creates then you will slowly eat through your available memory. You could
in this case free it in the caller after you had used it. However with this
sort of code it is normally better to pass an extra argument of a pointer
to a buffer created in the caller.
--
-----------------------------------------
-----------------------------------------