C | How to allocate memory, say, exactly 136 bytes?

3600 views c

I need to allocate two chunks of memory 1B and 512B

For 1B - ok, it should be something like that:

`char* firstChunk = malloc (sizeof(char)); // because char can contain 1B`

But what with the second chunk?

answered question

512*sizeof(char) ?

What does your title have to do with the content of your question? malloc(136) sizeof(char) is always 1, there's no need to multiply by it, it just adds noise to the code.

1 Answer


A char is by definition always 1 byte (even if it's not 8 bits), so to allocate a specific number of bytes, just multiply in the malloc argument.

char *bytes = (char*)malloc(136 * sizeof(char));

Be aware, that you could also use calloc, which takes 2 arguments and gives you zero'd memory, which is often times more desirable.

char *bytes = (char*)calloc(136, sizeof(char));

posted this

Have an answer?


Please login first before posting an answer.