Reputation: 635
How to use a C string to contain multiple null characters \x00.
Upvotes: 3
Views: 1186
Reputation: 43999
A C string is only an array of chars terminated by a null character. However, if you treat it as an array, it can contain inner null characters:
char data[4] = { 'x', '\0', 'y', '\0' };
You have to be careful, however, as most of the standard library functions will not work, as they expect an C string ending with the first null character.
For example, strlen(data)
will return 1 in the example above, as it stops after the first null character.
Upvotes: 3
Reputation: 19372
C's string functions (eg strlen()
, printf()
, etc) assume that the buffer will be null-terminated. If you have a buffer with multiple 0x00 characters, then you can't use any functions which treat 0x00 as a null character.
So instead of using, eg, strcpy()
(or strncpy()
) you would use memcpy()
- to move the bytes of memory from one place to another, rather than relying on this null-terminated behavior.
Upvotes: 9
Reputation: 67266
All you have to do is something like
char* data = (char*)malloc( 8 ) ; // allocate space for 8 bytes
memset( data, 0, 8 ) ; // set all 8 bytes to 0's
Upvotes: 2