Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is null character included while allocating using malloc

I have been using C for quite sometime, and I have this trivial problem that I want to query about.

Say i want to create a character array that stores upto 1000 characters. Now, when I am using malloc for the same, then do I specify the size of array as 1001 character [ 1000 characters + null] or just 1000?

Also, say I came across this problem, then how could I have found the answer to this solution on my own, maybe by using some test programs. I understand the size of string is calculated without the null character, but when I am allocating the memory for the same, do I take into account the null character too?

like image 749
Kraken Avatar asked Jul 08 '13 08:07

Kraken


People also ask

Does strlen include null?

The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.

Does strcpy add NULL terminator?

Description. The strcpy() function copies string2, including the ending null character, to the location that is specified by string1.

Can we use malloc for string?

malloc() returns a void* pointer to a block of memory stored in the heap. Allocating with malloc() does not initialize any string, only space waiting to be occupied.To add a null-terminating character, you either have to do this yourself, or use a function like scanf() , which adds this character for you.

How do you allocate space in a string?

Space is allocated by calling malloc with the number of bytes needed (for strings this is always one more than the maximum length of the string to be stored): char *pc = malloc(MAXSTR + 1) ; // can hold a string of up to MAXSTR characters.


1 Answers

If you need that block for storing null-terminated string then yes, you need to explictly ask malloc() to allocate an extra byte for storing the null-terminator, malloc() will not do it for you otherwise. If you intend to store the string length somewhere else and so you don't need the null terminator you can get away without allocating the extra byte. Of course it's up to you whether you need null-termination for strings, just don't forget that C library string handling functions only work with null-terminated strings.

like image 57
sharptooth Avatar answered Sep 20 '22 18:09

sharptooth