Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating char array using malloc

Considering the following line:

char *p = malloc( sizeof(char) * ( len + 1 ) );

Why is sizeof(char) used? It's not necessary, is it? Or Is it just a matter of style?

What advantages does it have?

like image 495
Nyan Avatar asked Jun 25 '10 04:06

Nyan


People also ask

How do you dynamically allocate a character array?

Use the new() Operator to Dynamically Allocate Array in C++ Then, we dynamically allocate the char array and assign the corresponding values to its elements in the for loop body. Note that the delete operator must be explicitly called once the memory associated with the arr pointer is no longer needed.

Does char * need malloc?

As was indicated by others, you don't need to use malloc just to do: const char *foo = "bar"; The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable.

How do you allocate memory to the array of char pointers?

In C, the RAM should use the following code to allocate the two-dimensional array: *contents = (char**) malloc(sizeof(char*) * numRows); **contents = (char*) malloc(sizeof(char) * numColumns * numRows); for(i = 0; i < numRows; i++) (*contents)[i] = ( (**contents) + (i * numColumns) );


2 Answers

Yes, it's a matter of style, because you'd expect sizeof(char) to always be one.

On the other hand, it's very much an idiom to use sizeof(foo) when doing a malloc, and most importantly it makes the code self documenting.

Also better for maintenance, perhaps. If you were switching from char to wchar, you'd switch to

wchar *p = malloc( sizeof(wchar) * ( len + 1 ) );

without much thought. Whereas converting the statement char *p = malloc( len + 1 ); would require more thought. It's all about reducing mental overhead.

And as @Nyan suggests in a comment, you could also do

type *p = malloc( sizeof(*p) * ( len + 1 ) );

for zero-terminated strings and

type *p = malloc( sizeof(*p) * len ) );

for ordinary buffers.

like image 152
brainjam Avatar answered Oct 30 '22 17:10

brainjam


It serves to self-document the operation. The language defines a char to be exactly one byte. It doesn't specify how many bits are in that byte as some machines have 8, 12, 16, 19, or 30 bit minimum addressable units (or more). But a char is always one byte.

like image 39
Amardeep AC9MF Avatar answered Oct 30 '22 17:10

Amardeep AC9MF