basic malloc/free question 
Author Message
 basic malloc/free question

hi

i have problems to understand the malloc concept
concerning the following snippet (gnu c).
its just an example:

char *getStr() {
  char *a;

  a = (char *) malloc(12);
  a = "just a test";
  return(a);

Quote:
}

void main() {
  char *b;
  b = getStr();
  fprintf(stderr,"b: %s",b);

Quote:
}

b gives me the correct string. after printing out b, i want
to free the allocated memory. free(b) fails (sure).
normally everything what is defined within a function, loop
etc is freed by the system after passing it, or? malloc
things not, or i wouldnt get the proper string in b, or?

any help/hint/explanation would be great

greetings
ben



Sat, 03 Jan 2004 07:14:17 GMT  
 basic malloc/free question
Quote:

> hi

> i have problems to understand the malloc concept
> concerning the following snippet (gnu c).
> its just an example:

> char *getStr() {
>   char *a;

>   a = (char *) malloc(12);

Don't cast the return value of malloc(). It's unnecessary and can hide
other errors.
Quote:
>   a = "just a test";

This line does not do what you think. What the line, as written, does is
set `a' to the address of the string literal "just a test" (creating a
memory leak in the process, as you can no longer get to the malloc()-ed
memory from above). ITYM:
    strcpy(a, "just a test");
Quote:
>   return(a);
> }

> void main() {

Repeat after me: `main()' returns int `main()' returns int `main()' ...
Quote:
>   char *b;
>   b = getStr();

Now, since `b' really is a pointer to malloc()-ed memory...
Quote:
>   fprintf(stderr,"b: %s",b);

... free(b);
will work correctly.
Quote:
> }

> b gives me the correct string. after printing out b, i want
> to free the allocated memory. free(b) fails (sure).
> normally everything what is defined within a function, loop
> etc is freed by the system after passing it, or? malloc
> things not, or i wouldnt get the proper string in b, or?

See above.

HTH,
--ag
--
Artie Gold, Austin, TX  (finger the cs.utexas.edu account for more info)

--
"fsck" is not an obcenity



Sat, 03 Jan 2004 07:33:56 GMT  
 basic malloc/free question

Quote:

> hi

> i have problems to understand the malloc concept
> concerning the following snippet (gnu c).
> its just an example:

> char *getStr() {
>   char *a;

>   a = (char *) malloc(12);

Drop the "(char *)".  It leads to errors, such as omitting an
include file.

Quote:
>   a = "just a test";

This overwrites the pointer you just got, creating a memory leak.
You want

   strcpy(a, "just a test");

to copy the fixed string into the allocated memory.

Quote:
>   return(a);
> }

> void main() {
>   char *b;
>   b = getStr();
>   fprintf(stderr,"b: %s",b);
> }

> b gives me the correct string. after printing out b, i want
> to free the allocated memory. free(b) fails (sure).
> normally everything what is defined within a function, loop
> etc is freed by the system after passing it, or? malloc
> things not, or i wouldnt get the proper string in b, or?

See above.

--

   (Remove "XXXX" from reply address. my-deja works unmodified)



Sat, 03 Jan 2004 07:28:58 GMT  
 basic malloc/free question

Quote:


> > hi

> > i have problems to understand the malloc concept
> > concerning the following snippet (gnu c).
> > its just an example:

> > char *getStr() {
> >   char *a;

> >   a = (char *) malloc(12);

> Drop the "(char *)".  It leads to errors, such as omitting an
> include file.

Nonsense!

Sorry, Chuck, but it really is.

It can *hide* the error of omitting <stdlib.h>, to be sure, but to claim
that it *leads* to that error is seriously overstating the case IMHO.

<snip>

Quote:

> > void main() {

Oopsie, Chuck, and you missed this...

I prescribe more coffee. :-)

--

"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton



Sat, 03 Jan 2004 07:48:06 GMT  
 basic malloc/free question

Quote:



> > > hi

> > > i have problems to understand the malloc concept
> > > concerning the following snippet (gnu c).
> > > its just an example:

> > > char *getStr() {
> > >   char *a;

> > >   a = (char *) malloc(12);

> > Drop the "(char *)".  It leads to errors, such as omitting an
> > include file.

> Nonsense!

> Sorry, Chuck, but it really is.

> It can *hide* the error of omitting <stdlib.h>, to be sure, but to claim
> that it *leads* to that error is seriously overstating the case IMHO.

    Either way, it should never be done. There is no reason to cast
malloc()'s return value.

--
Clark S. Cox III

http://www.whereismyhead.com/clark/



Sat, 03 Jan 2004 08:11:54 GMT  
 basic malloc/free question
hi again

thx for the fast help,great. strcpy ok, got it.
and now and for all times: int main()

just another thing:
to handle strings containing '\0' strcpy will
fail ( i guess ).
either this way:

<snip>
a = malloc(sizeof(char)*3);
a[0]=97;  // ascii "a";
a[1]=0;
a[2]=99;  // "c"
return(a)
</snip>

or memcpy, right?

greetings
ben



Sat, 03 Jan 2004 08:34:00 GMT  
 basic malloc/free question

Quote:

> hi again

> thx for the fast help,great. strcpy ok, got it.
> and now and for all times: int main()

> just another thing:
> to handle strings containing '\0' strcpy will
> fail ( i guess ).

    A string cannot contain a '\0', except for the terminating
character. The '\0', by definition, marks the end of the string.

Quote:
> either this way:

> <snip>
> a = malloc(sizeof(char)*3);
> a[0]=97;  // ascii "a";
> a[1]=0;
> a[2]=99;  // "c"
> return(a)
> </snip>

    If you mean 'c', say 'c', not 99. Your code will be more portable,
and more readable, and won't need those comments.

--
Clark S. Cox III

http://www.whereismyhead.com/clark/



Sat, 03 Jan 2004 08:37:15 GMT  
 basic malloc/free question

Quote:

> hi

> i have problems to understand the malloc concept
> concerning the following snippet (gnu c).
> its just an example:

> char *getStr() {
>   char *a;

>   a = (char *) malloc(12);

Had you included <stdlib.h>, you would not be tempted to use the cast.
You should just use
   a = malloc(12);
and enable enough compiler warnings that this gives a diagnostic when
you do not remember to include <stdlib.h>

Quote:
>   a = "just a test";

This reassigns a to point to a string literal "just a test" and loses the
results of the malloc().  You probably want
   strcpy(a,"just a test");

Quote:
>   return(a);
> }

> void main() {
>   char *b;
>   b = getStr();
>   fprintf(stderr,"b: %s",b);
> }

> b gives me the correct string. after printing out b, i want
> to free the allocated memory. free(b) fails (sure).

It fails because the pointer is to a string literal, not to your malloced
memory.
Quote:
> normally everything what is defined within a function, loop
> etc is freed by the system after passing it, or? malloc
> things not, or i wouldnt get the proper string in b, or?

> any help/hint/explanation would be great



Sat, 03 Jan 2004 08:54:16 GMT  
 basic malloc/free question

Quote:


> > > hi

> > > i have problems to understand the malloc concept
> > > concerning the following snippet (gnu c).
> > > its just an example:

> > > char *getStr() {
> > >   char *a;

> > >   a = (char *) malloc(12);

> > Drop the "(char *)".  It leads to errors, such as omitting an
> > include file.

> Nonsense!

> Sorry, Chuck, but it really is.

> It can *hide* the error of omitting <stdlib.h>, to be sure, but to claim
> that it *leads* to that error is seriously overstating the case IMHO.

I'm going to have to disagree.

SAMPLE 1:

$ cat bar.c

int             main()
{
    char *foo = malloc(10);
    return 0;

Quote:
}


$ gcc bar.c
bar.c: In function `main':
bar.c:4: warning: initialization makes pointer from integer without a cast

SAMPLE 2:


$ cat bar2.c

int             main()
{
    char *foo = (char *)malloc(10);
    return 0;

Quote:
}


$ gcc bar2.c


$

Now, suppose that you happened to type in both of these programs.  I can
tell you for sure that I have left out standard headers.  I will surely
catch the error immediately if I don't cast it, and will be less likely to
catch it if I cast it.  Hence, the cast will *generate* errors because it
hides diagnostics.

Now, quite likely I will catch it at some point.  But I agree with
CBFalconer that the cast does _generate_ errors.
--
C-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 "The C-FAQ Book" ISBN 0-201-84519-9
C.A.P. FAQ: ftp://cap.connx.com/pub/Chess%20Analysis%20Project%20FAQ.htm



Sat, 03 Jan 2004 08:20:10 GMT  
 basic malloc/free question
hi folx

well, it wasnt my intention to open up a discussion
about casting malloc, but there are interesting
postings

all i can say is that i obtained most of my little
c knowledge from the gnu c website, where every
malloc is casted

cite:
You can store the result of malloc into any pointer variable
without a cast, because ISO C automatically converts the type
void * to another type of pointer when necessary. But the
cast is necessary in contexts other than assignment operators
or if you might want your code to run in traditional C.  

http://www.gnu.org/manual/glibc-2.2.3/html_node/libc_24.html#SEC25

greetings
ben



Sat, 03 Jan 2004 09:40:32 GMT  
 basic malloc/free question

Quote:

> all i can say is that i obtained most of my little
> c knowledge from the gnu c website, where every
> malloc is casted

GNU C documentation is a lousy place to find out about the C
programming language.  GNU C and ISO C are different, in some
ways subtly, in some ways sharply.  You'd be better off looking
at a real C reference manual.

--
"You call this a *C* question? What the hell are you smoking?" --Kaz



Sat, 03 Jan 2004 09:42:30 GMT  
 basic malloc/free question

Quote:



>> It can *hide* the error of omitting <stdlib.h>, to be sure, but to claim
>> that it *leads* to that error is seriously overstating the case IMHO.

>I'm going to have to disagree.

>SAMPLE 1:

>$ cat bar.c

>int             main()
>{
>    char *foo = malloc(10);
>    return 0;
>}


>$ gcc bar.c
>bar.c: In function `main':
>bar.c:4: warning: initialization makes pointer from integer without a cast

>SAMPLE 2:


>$ cat bar2.c

>int             main()
>{
>    char *foo = (char *)malloc(10);
>    return 0;
>}


>$ gcc bar2.c


>$

>Now, suppose that you happened to type in both of these programs.  I can
>tell you for sure that I have left out standard headers.  I will surely
>catch the error immediately if I don't cast it, and will be less likely to
>catch it if I cast it.  Hence, the cast will *generate* errors because it
>hides diagnostics.

No; it was forgetfulness, sloppiness, distractedness, or something
similar on the part of the person who typed the code (or, more likely
in some cases, the person who wrote it in the first place) that caused
the error; casting malloc just stopped it from being caught the first
time the code was compiled.

dave

--

In comp.lang.c, the sanity of the implementation is not as important as
its conformance to the Standard.
                                    --Richard Heathfield in comp.lang.c



Sat, 03 Jan 2004 10:01:50 GMT  
 basic malloc/free question

Quote:




> >> It can *hide* the error of omitting <stdlib.h>, to be sure, but to
claim
> >> that it *leads* to that error is seriously overstating the case IMHO.

> >I'm going to have to disagree.

> >SAMPLE 1:

> >$ cat bar.c

> >int             main()
> >{
> >    char *foo = malloc(10);
> >    return 0;
> >}


> >$ gcc bar.c
> >bar.c: In function `main':
> >bar.c:4: warning: initialization makes pointer from integer without a
cast

> >SAMPLE 2:


> >$ cat bar2.c

> >int             main()
> >{
> >    char *foo = (char *)malloc(10);
> >    return 0;
> >}


> >$ gcc bar2.c


> >$

> >Now, suppose that you happened to type in both of these programs.  I can
> >tell you for sure that I have left out standard headers.  I will surely
> >catch the error immediately if I don't cast it, and will be less likely
to
> >catch it if I cast it.  Hence, the cast will *generate* errors because it
> >hides diagnostics.

> No; it was forgetfulness, sloppiness, distractedness, or something
> similar on the part of the person who typed the code (or, more likely
> in some cases, the person who wrote it in the first place) that caused
> the error; casting malloc just stopped it from being caught the first
> time the code was compiled.

Hiding errors causes errors.
--
C-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 "The C-FAQ Book" ISBN 0-201-84519-9
C.A.P. FAQ: ftp://cap.connx.com/pub/Chess%20Analysis%20Project%20FAQ.htm


Sat, 03 Jan 2004 11:00:42 GMT  
 basic malloc/free question

Quote:

<casting malloc>

> Now, quite likely I will catch it at some point.  But I agree with
> CBFalconer that the cast does _generate_ errors.

Casts don't generate errors. Programmers do.

--

"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton



Sat, 03 Jan 2004 19:27:21 GMT  
 basic malloc/free question

Quote:

> > a[0]=97;  // ascii "a";
> > a[1]=0;
> > a[2]=99;  // "c"

>     If you mean 'c', say 'c', not 99. Your code will be more portable,
> and more readable, and won't need those comments.

Not necessarily more portable.  If the characters are going to a
device that expects ASCII encoding, and the execution character set is
something incompatible, 99 does the job but 'c' doesn't.

I'd prefer a separate conversion function, though.



Sun, 04 Jan 2004 00:17:28 GMT  
 
 [ 25 post ]  Go to page: [1] [2]

 Relevant Pages 

1. malloc - Basic Question

2. Basic question on freeing

3. malloc, realloc, free questions

4. malloc/free questions

5. malloc - free question

6. malloc/free question

7. Dumb question concerning malloc/free

8. a question about malloc and free

9. simple question about malloc & free

10. dumb malloc free question

11. malloc/free question with Purify

12. malloc(), free(), and strtok() questions

 

 
Powered by phpBB® Forum Software