Newbie question: malloc() function 
Author Message
 Newbie question: malloc() function

Hello,

I am a completely newbie in C. I have a question about the function
malloc(), hope somebody can help me.

Method 1 :
/* allocate memory for a 100 character string */
char *str;
str = malloc(100 * sizeof(char));

Method 2:
/* allocate memory for a 100 character string */
char *str;
str = (char *) malloc(100 * sizeof(char));

My question is why do i need to include (char *) to allocate memory,
as method 1 can also do the job. I 've checked some book, they said
malloc() returns  a pointer to the allocated block of memeory,
therefore why do we need to include (char *) in the statement?

Sorry for my poor english.
Thank you.

Allen

ICQ: 8805558



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

Quote:

> Hello,

> I am a completely newbie in C. I have a question about the function
> malloc(), hope somebody can help me.

> Method 1 :
> /* allocate memory for a 100 character string */
> char *str;
> str = malloc(100 * sizeof(char));

> Method 2:
> /* allocate memory for a 100 character string */
> char *str;
> str = (char *) malloc(100 * sizeof(char));

> My question is why do i need to include (char *) to allocate memory,
> as method 1 can also do the job. I 've checked some book, they said
> malloc() returns  a pointer to the allocated block of memeory,
> therefore why do we need to include (char *) in the statement?

Method-1 and Method-2 do exactly the same...
may be you didn't
  #include <malloc.h>
so the Compiler assumes that malloc() is a function returning int.
Assigning an 'int' to a 'char *' will generate a warning (at least) at
compiletime.

Another remark:
  malloc(100 * sizeof(char)) is the same as malloc(100) because
  sizeof(char) is 1 (per definition, this has been mentioned very often in
c.l.c)

Anyway: typecasts like the one you placed before malloc() in method-2 don't
  perform any action (no code is generated for them), they just supress
  compiler-warnings. Usually method-1 is the better choice, because
  in malloc.h you'll find malloc() being defined as a function returning
'void *'.
  Assigning a 'void *' to a 'char *' is legal without warning.

Regards Rainer



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

Quote:

>I am a completely newbie in C. I have a question about the function
>malloc(), hope somebody can help me.

>Method 1 :
>/* allocate memory for a 100 character string */
>char *str;
>str = malloc(100 * sizeof(char));

Fine.  Note that sizeof(char) is always 1 so you can quite safely just do

  str = malloc (100);

But don't worry about this if you're not happy with it; your version is
perfectly OK, and there's time enough for the niceties later.

Quote:
>Method 2:
>/* allocate memory for a 100 character string */
>char *str;
>str = (char *) malloc(100 * sizeof(char));

>My question is why do i need to include (char *) to allocate memory,
>as method 1 can also do the job.

Well -- you don't.  Indeed including the (char *) is often seen as
harmful because it can mask certain errors.

The question is why you think you need it.  If your compiler is spitting
out the program without the (char *) -- which is, by the way, known as a
cast -- then check you really are invoking it as a C compiler, not as a
C++ compiler.  In particular make sure your source file is called
something.c rather than something.cpp or anything else.

If that's OK, make sure you are including <stdlib.h>.  If this doesn't
help either, post a short complete program and the error messages and
I'm sure somebody will be able to help.

If you've read a book or seen some code where the cast is used, then the
best advice is just to ignore it.  There was once a time when the cast
was necessary, but with the current language definition, it isn't.  Some
people are still stuck in old habits or concerned about portability to
older compilers.

Quote:
>Sorry for my poor english.

Your English is fine.

Cheers,
Richard
--
Richard Stamp
Churchill College, Cambridge



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function


Quote:

>Method-1 and Method-2 do exactly the same...
>may be you didn't
>  #include <malloc.h>
>so the Compiler assumes that malloc() is a function returning int.
>Assigning an 'int' to a 'char *' will generate a warning (at least) at
>compiletime.

Right, except that in Standard C malloc is declared in <stdlib.h>, not
<malloc.h>.  I know that some implementations do provide a <malloc.h>
but this is not portable.

Cheers,
Richard
--
Richard Stamp
Churchill College, Cambridge



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

|Hello,
|
|I am a completely newbie in C. I have a question about the function
|malloc(), hope somebody can help me.
|
|Method 1 :
|/* allocate memory for a 100 character string */
|char *str;
|str = malloc(100 * sizeof(char));
|
|Method 2:
|/* allocate memory for a 100 character string */
|char *str;
|str = (char *) malloc(100 * sizeof(char));

Both of the above contain the text `* sizeof(char)'.  Since, by
definition, sizeof(char) == 1, this is unnecessary.  OTOH, suppose
the elements of str might be some wider type than char.  This
is quite possible when code is internationalized, for example.
Now
    str = malloc(100);    /* or str = malloc(100*sizeof(char)); */
will not do.  A safer approach is
    str = malloc(100 * sizeof *str);
This still contains the {*filter*} hardwared constant 100.  I'm
sure you can find a way to make it go away.

|My question is why do i need to include (char *) to allocate memory,

You don't, as long as your programming language is C.
The problem is that in C
    str = malloc(100 * stizeof *str);
is good style and the cast is poor style, in
C++, the cast is required.  OTOH, in C++ the use
of malloc is frowned on, so it should be a non-issue.

|as method 1 can also do the job. I 've checked some book, they said
|malloc() returns  a pointer to the allocated block of memeory,
|therefore why do we need to include (char *) in the statement?

The main effect of the (char *) is to mask the failure to
#include <stdlib.h>
This masking is a bad thing, so the cast is also a bad thing.



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

<snip>
|Method-1 and Method-2 do exactly the same...
|may be you didn't
|  #include <malloc.h>
|so the Compiler assumes that malloc() is a function returning int.

Since <malloc.h> is not a standard header (and usually represents
older non-standard approaches), it is a GoodIdea(TM) to
never #include it.  But #include <stdlib.h> is called for.



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function



...

Quote:
>Method-1 and Method-2 do exactly the same...
>may be you didn't
>  #include <malloc.h>

Don't use <malloc.h>, it is non-standard. malloc() is declared in the
standard C header <stdlib.h>

Quote:
>so the Compiler assumes that malloc() is a function returning int.
>Assigning an 'int' to a 'char *' will generate a warning (at least) at
>compiletime.

And even if the cast silences the warning the code is still wrong since int
values could be returned in a different way to pointer values.

...

Quote:
>Anyway: typecasts like the one you placed before malloc() in method-2 don't
>  perform any action (no code is generated for them),

That depends on the platform. It is likely true in the case where malloc is
properly declared as returning void * since char * and void * are guaranteed
to have the same representation. An int to char * cast might well produce
conversion code which would clearly be wrong in this case.

--
-----------------------------------------


-----------------------------------------



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function


Quote:

>Just a few small points.

>Firstly, char may be more than one byte in size on other platforms. It

Oh dear, here we go again. :) Or maybe not, since you are in
possession of the right document.

Quote:
>may even contain more than an octet of bits per byte ! The Standard
>only states at least the range -127 to 127 should be supported.It may

Yes.

Quote:
>very well be more. Therefore you should not assert that 'sizeof(char)
>== 1' is always true.

Ah, but read the definition of ``byte'' in clause 3.


Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

[SNIP]

Quote:
> Method-1 and Method-2 do exactly the same...
> may be you didn't
>   #include <malloc.h>
> so the Compiler assumes that malloc() is a function returning int.
> Assigning an 'int' to a 'char *' will generate a warning (at least) at
> compiletime.

> Another remark:
>   malloc(100 * sizeof(char)) is the same as malloc(100) because
>   sizeof(char) is 1 (per definition, this has been mentioned very often in
> c.l.c)

> Anyway: typecasts like the one you placed before malloc() in method-2 don't
>   perform any action (no code is generated for them), they just supress
>   compiler-warnings. Usually method-1 is the better choice, because
>   in malloc.h you'll find malloc() being defined as a function returning
> 'void *'.
>   Assigning a 'void *' to a 'char *' is legal without warning.

[SNIP]

Just a few small points.

Firstly, char may be more than one byte in size on other platforms. It
may even contain more than an octet of bits per byte ! The Standard
only states at least the range -127 to 127 should be supported.It may
very well be more. Therefore you should not assert that 'sizeof(char)
== 1' is always true.Secondly, the original poster allocated room for
a 100 character strings.However, he neglected to also allocate room
for the nul char i.e. instead of

char str = malloc(sizeof(char)*100);

he should have written something like this.

char str = malloc(sizeof(char)*(100 + 1));

On a style note, try to use a symbolic constant, rather than a
literal. For example, the way below has two advantages. Firstly,
there is a strong semantic connection between the amount of
memory being allocated and its intended use. Secondly, if later
in the program you decide to support strings of another length,
you simply change the value of one preprocessor directive, rather
than making manual adjustments in your translation unit.

#define STRSZ 100
char str = malloc(sizeof(char)*(STRSZ + 1));

Thirdly, note that if you use fgets() to read your string, you may need
to specify an extra character, because fgets() also reads in the newline
character, if any. Finally, you must ALWAYS check the return value from
malloc(). The code as written, makes an assumption that the memory
request was valid.For example, you could have written

#define STRSZ 100

int main(void){
  char str = malloc(sizeof(char)*(STRSZ + 2));
  if( str == NULL )
    exit( EXIT_FAILURE );
  return EXIT_SUCCESS;

Quote:
}

--
Scarab.
#include < cfaq.h >
int main(void){
  return LEARNING_SUCCESS;

- Show quoted text -

Quote:
}



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function


Quote:

>Firstly, char may be more than one byte in size on other platforms. It
>may even contain more than an octet of bits per byte ! The Standard
>only states at least the range -127 to 127 should be supported.It may
>very well be more.

True.

Quote:
>Therefore you should not assert that 'sizeof(char)
>== 1' is always true.

But it is!  It tells you how many chars there are in an object of
type 'char'.

What do you think sizeof() reports?  Size in... octets?  Why would
you care, and what if you can't measure the size of a 12-bit object
in 8-bit octets?

-s
--

C/Unix wizard, Pro-commerce radical, Spam fighter.  Boycott Spamazon!
Not speaking for my employer.  Questions on C/Unix?  Send mail for help.
Visit my new ISP <URL:http://www.plethora.net/> --- More Net, Less Spam!



Tue, 12 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function


Quote:

>Firstly, char may be more than one byte in size on other platforms. It
>may even contain more than an octet of bits per byte ! The Standard
>only states at least the range -127 to 127 should be supported.It may
>very well be more. Therefore you should not assert that 'sizeof(char)
>== 1' is always true.

No, sizeof(char) == 1 is indeed true.  The following is a rehash of
something I wrote a few months ago:

The reason this causes confusion is that there are (at least) three
conflicting definitions for "byte".

(a) The Standard defines "byte" to mean (I'm abstracting a bit, but this
    is basically right) "the size of a variable of type 'char'".  I'll
    call this a "Standard byte".

(b) Many people use the word "byte" to mean "the smallest addressable
    unit on the architecture in question".  I'll call this a "machine
    byte".

(c) And the majority of people, of course, just use "byte" to mean
    "eight bits".  I'll call that an "octet".

Now, sizeof() yields the size of its operand in Standard bytes.  So,
sizeof(char) is always 1.  As you correctly observe, the minimum
range of 'char' means this must correspond to at least an octet, but
it could reasonably be more.

For example, perhaps we're dealing with some kind of extended character
set and we want to be able to hold a larger range of character codes
in a 'char'.  So the length of a 'char' increases, and so does the
length of a Standard byte.  Of course, this doesn't affect the size
of the machine byte.  If the smallest addressable unit is 8 bits, we
could quite reasonably end up with one Standard byte equal to two
machine bytes or more.

Coming at it the other way, suppose the machine byte is 64 bits
(I understand this is the case with some RISC processors).  Now, the
implementor has a choice to make: either make a 'char', and hence
the Standard byte, 64 bits (which is quite legal but a little odd),
or leave it at 8 bits (say) and do some sort of unpacking where
necessary.  Then, we end up with a Standard byte being smaller than
a machine byte.

It's just a terminology thing.

Cheers,
Richard
--
Richard Stamp
Churchill College, Cambridge



Wed, 13 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

[SNIP]

Quote:
> #define STRSZ 100

> int main(void){
>   char str = malloc(sizeof(char)*(STRSZ + 2));
>   if( str == NULL )
>     exit( EXIT_FAILURE );
>   return EXIT_SUCCESS;
> }

[SNIP]

Whoops !
Scarab Damage Control Team take over...

#include <stdlib.h>
#define STRSZ 100

int main(void){
  char str = malloc(sizeof(char)*(STRSZ+2));
  if(str == NULL)
    exit(EXIT_FAILURE);

  /* use str */

  if(str != NULL)
    free(str);

  return EXIT_SUCCESS;

Quote:
}

regards,
--
Scarab.
#include < cfaq.h >
int main(void){
  return LEARNING_SUCCESS;
Quote:
}



Wed, 13 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

|Firstly, char may be more than one byte in size on other platforms.

Does no one read the standard any more before claiming to be an
expert?  We are talking about C here.  Your fantasies don't count.
Start with the definition of byte (3.4), the definition of char (6.1.2.5),
and of sizeof (6.3.3.4)

| It
|may even contain more than an octet of bits per byte ! The Standard
|only states at least the range -127 to 127 should be supported.It may
|very well be more. Therefore you should not assert that 'sizeof(char)
|== 1' is always true.

I understand that you are getting the ISO committees to accept
you amendation to the standard, which in the discussion of sizeof
in 6.3.3.4 states:
"When applied to an operand that has type char, unsigned char, or
signed char, (or a qualified version thereof) the result is 1."

If this flat statement in the standard is in error, you should quickly
let all the C implementors share your insight.



Wed, 13 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

Quote:

> I am a completely newbie in C. I have a question about the function
> malloc(), hope somebody can help me.

> Method 1 :
> /* allocate memory for a 100 character string */
> char *str;
> str = malloc(100 * sizeof(char));

> Method 2:
> /* allocate memory for a 100 character string */
> char *str;
> str = (char *) malloc(100 * sizeof(char));

> My question is why do i need to include (char *) to allocate memory,
> as method 1 can also do the job. I 've checked some book, they said
> malloc() returns  a pointer to the allocated block of memeory,
> therefore why do we need to include (char *) in the statement?

Good question - the answer is that you don't need to have (char *)... in
fact, it is recommended that you DON'T write it, since it can only hide
stupid mistakes like forgetting to include <stdlib.h>.  By the way, if
you really want a 100-character string you need to allocate 101 bytes
(100 characters + '\0').

Note: If you ever switch to C++, then you will need the cast because
void pointers cannot be implicitly converted to other types.  It does
not hide any errors since you MUST include <stdlib.h> to avoid errors.

--

I believe we can change anything.
I believe in my dream.
    - Joe Satriani



Wed, 13 Sep 2000 03:00:00 GMT  
 Newbie question: malloc() function

===================================
#include <stdlib.h>
#define STRSZ 100

int main(void){
  char str = malloc(sizeof(char)*(STRSZ+2));
  if(str == NULL)
    exit(EXIT_FAILURE);

  /* use str */

  if(str != NULL)
    free(str);

  return EXIT_SUCCESS;

Quote:
}

===================================

My remarks:

* sizeof(char) is _always_ one.
* Why STRSZ + 2?  It only takes one character to hold '\0'.
* That should be char *str =..., not char str = ...
* Since you exited if str was null, the check prior to free() is not needed.
* Since this code is in main(), is there any reason to exit(EXIT_FAILURE)
instead of return EXIT_FAILURE?

Please reply publicly or disregard the e-mail address in the header.  Use
'syd' at the commercial internet service provider Netroplex instead.
Thanks.



Wed, 13 Sep 2000 03:00:00 GMT  
 
 [ 23 post ]  Go to page: [1] [2]

 Relevant Pages 

1. newbie question about malloc

2. Newbie question: using malloc() to create a string?

3. malloc question from newbie

4. newbie malloc/array type question

5. Newbie malloc question!

6. Newbie question on malloc

7. simple malloc question in functions

8. question, malloc in a function

9. C question : redefining a new malloc() calling standard malloc()

10. to malloc() or not to malloc(), that is the question

11. newbie question: returning structs from functions

 

 
Powered by phpBB® Forum Software