newbie: malloc and free

N

neon

hi! Im a student studying C.. I have some problem understanding the
malloc() and free() function..

does by calling free() from the caller, deallocate the heap used by
variable newString in function StringCopy? if not, how wil I deallocate
the heap used by the StringCopy?

thanks in advance!

/*main Caller */
int main(void){
char string[80];
stringcopy(string);
free(string);
....
....
}

/* function */
char* StringCopy(const char* string)
{
char *newString;
newString = malloc(sizeof(char)*len);
strcpy(newString, string);
....
....
return(newString);
}
 
R

ranveerkunal

this code will end up giving segmentation fault;
because you are trying to free a memory (string) that is on the stack;
to deallocate the memory used by stringcopy

free(stringcopy(string));
 
A

Al Bowers

neon said:
hi! Im a student studying C.. I have some problem understanding the
malloc() and free() function..

does by calling free() from the caller, deallocate the heap used by
variable newString in function StringCopy? if not, how wil I deallocate
the heap used by the StringCopy?
You need to make string a char *, which is assigned the
value returned by function StringCopy. This value represents
a pointer to the dynamically allocated space or the value NULL
should there be a failure to allocate the space. Once you are
finished with the allocation, then you free it using the
value returned by function StringCopy. Inserted is this
correction plus other problem areas.

#include <stdlib.h>
#include <string.h>
#include said:
/* Function Prototype */
char* StringCopy(const char* string);
> /*main Caller */
> int main(void){
> char string[80];


make this
char *string;
> stringcopy(string);


string = Stringcopy("This is a test string");
if(string != NULL) puts(string);
> free(string);
> ...
> ...
> }
>
> /* function */
> char* StringCopy(const char* string)
> {
> char *newString;
> newString = malloc(sizeof(char)*len);


newString = malloc(strlen(string)+1);
> strcpy(newString, string);


if(newString != NULL) strcpy(newString, string);
 
N

neon

I mean how will I deallocate the str1 var of function stralloc.. I know
that after the function has finished its routine, all memory that was
used by the function are returned to the stack.. how about the malloc
inside of a function?, It used the heap not the stack.. you can only
deallocate it using free() and you can't free the variable when you
still need it "return(str1)".. that make me confuse,on how to
deallocate the memory used by the variable in a function..

thanks ranveerkunal!
sorry with my english :)
 
R

Richard Bos

neon said:
does by calling free() from the caller, deallocate the heap used by
variable newString in function StringCopy? if not, how wil I deallocate
the heap used by the StringCopy?

There's no requirement that the memory for allocated memory is kept in a
heap structure, but yes, calling free() on a pointer to block of memory
you got from malloc() frees that memory, regardless of the scope of the
variable you first assigned that pointer to. Well, as long as you
haven't realloc()'ed it in the mean time, in which case you need to use
the new value; or have already free()d it: you shouldn't do it twice.

But that's not what's going on here. You're passing the right thing to
malloc(); but not to free(). Let's rearrange your code a bit, so it's
easier to see what's going on:
char* StringCopy(const char* string)
[ First, minor, bug: "string" is an identifier that's reserved for use
by the implementation. All identifiers starting with str and a lower-
case letter are said:
{
char *newString;
newString = malloc(sizeof(char)*len);

[ Second bug: _what_ len? strlen(string) is wrong, because you want one
more byte to hold the terminating '\0'. Oh, and sizeof(char) is
guaranteed to be 1.]
[ Third bug, relevant to serious programs, not to tests: always check
that malloc() didn't return a null pointer. ]
strcpy(newString, string);
return(newString);
}

Ok, so up to here, apart from that length, it's OK. You're taking a
string; allocating memory for a copy of it; copying the string into the
new memory; and passing the pointer out. Correctly. If the calling
function stores the return value of StringCopy() somewhere, and later
calls free() on that value, that is a correct use of malloc() and
free(). (Note also that StringCopy() does _nothing_ to either the value
or the contents of string.) However...
int main(void){
char string[80];
[ I'm assuming you put some content into string, here. ]
stringcopy(string);
[ I'm also assuming that you actually meant StringCopy - copy&paste,
don't retype, your code; typos are easy to make. ]

....you are _not_ assigning the return value of StringCopy() to anything.
Therefore, that pointer value is now lost; and since it was the only
pointer to your block of allocated memory, so is that block. (Note that,
as above, string itself has not been touched.)
free(string);

Since string is an array in main(), and not a pointer to a block of
allocated memory, you can't pass it to free().

Here's a corrected version of your code:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

char* StringCopy(const char* str)
{
char *newString;

newString = malloc(strlen(str)+1);
if (newString)
strcpy(newString, string);

return(newString); /* Yes, even when it's null. */
}

int main(void)
{
char oldstr[80]="This is a test.";
char *newstr;

newstr=StringCopy(string);
if (newstr) /* This is why we could return a null pointer from
StringCopy(): we're checking it here. */
printf("Lo and behold: %s; %s!\n", oldstr, newstr);
else
puts("StringCopy() could not get the memory it needed.");

free(newstr); /* This is legal even when newstr==NULL. */
/* You can't use newstr after this, until you give it a new value.
oldstr, OTOH, is still fine. */

return 0;
}

Richard
 
R

Richard Bos

this code

_What_ code? Post with context, dammit! Google's braindead Beta Groups
interface is no excuse for you to be a bad netizen.
will end up giving segmentation fault;

_May_ end up causing a segfault. It certainly _does_ cause undefined
behaviour, but the result in practice can be anything, including a
segfault, but ignoring the free() call is also legal, and so is
corrupting your data.
because you are trying to free a memory (string) that is on the stack;

Has not been dynamically allocated; where it _is_ is not as important as
where it did not come from.
to deallocate the memory used by stringcopy

free(stringcopy(string));

That would be legal, but entirely useless.

Richard
 
B

Barry Schwarz

hi! Im a student studying C.. I have some problem understanding the
malloc() and free() function..

does by calling free() from the caller, deallocate the heap used by

Forget heap (it is an implementation detail not all implementations
have). Think of dynamically allocated memory.
variable newString in function StringCopy? if not, how wil I deallocate
the heap used by the StringCopy?

thanks in advance!

/*main Caller */
int main(void){
char string[80];
stringcopy(string);
free(string);

You cannot free string since it was not allocated with any of the
malloc related functions.

You want to free the area allocated in StringCopy. You even go to the
trouble of returning the address of the allocated area.
Unfortunately, main makes no effort to keep this address. If you add
char *string2;
to your declarations and change the function call to
string2 = ...
and fix the typos associated with the function name, then main will
have the address and when it is appropriate you can call free with
free(string2);
...
...
}

/* function */
char* StringCopy(const char* string)
{
char *newString;
newString = malloc(sizeof(char)*len);
len???

strcpy(newString, string);
...
...
return(newString);
}



<<Remove the del for email>>
 
N

neon

thank's peep's for enlighten me and point some of the problem with my
code! thank's again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,113
Latest member
Vinay KumarNevatia
Top