Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null terminated string in C

Tags:

c

string

null

I am quite anxious about strings in C. Do I need to set the last char \0 or it does it by it self? If I don't do it manually then when I try to debug code and when I access string1[257] it is not null. I am having problems with freeing allocated memory of an array of strings so I thought it was a reason.

char string1[257], string2[257];
scanf("%s", &string2);
string1[257] = '\0';
strncpy(string1, string2, 257);
string1[257] = '\0'; /* do I need to do that? */
like image 266
Arturs Vancans Avatar asked Nov 20 '11 16:11

Arturs Vancans


4 Answers

String literals like "Hello World!" are null-terminated, but char arrays are not automatically null terminated.

The general principle I've always taken is to be extra cautious and assign '\0' to the the end of the string unless that causes a performance problem. In those cases, I'm extra careful about which library functions I use.

like image 94
Michael Price Avatar answered Sep 21 '22 00:09

Michael Price


A literal string like "foo\nbar" is always translated to a const char literal[] with an additional zero byte at the end. (So the constant would have 8 bytes, the first being f and the last being zero).

But you are right in forcing explicitly the last byte to 0 after a strncpy.

And as Aurelio De Rosa remarked, the last correct index is 256 for an array [257].

like image 29
Basile Starynkevitch Avatar answered Sep 21 '22 00:09

Basile Starynkevitch


Always be careful to allocate enough memory with strings, compare the effects of the following lines of code:

char s1[3] = "abc";
char s2[4] = "abc";
char s3[] = "abc";

All three are considered legal lines of code (http://c-faq.com/ansi/nonstrings.htmlhttp://c-faq.com/ansi/nonstrings.html), but in the first case, there isn't enough memory for the fourth null-terminated character. s1 will not behave like a normal string, but s2 and s3 will. The compiler automatically count for s3, and you get four bytes of allocated memory. If you try to write

s1[3] = '\0';

that's undefined behavior and you're writing to memory that doesn't belong to s1, and would have weird effects, maybe even disrupting malloc's backend information, making it hard to free memory.

like image 21
RobotNinja Avatar answered Sep 22 '22 00:09

RobotNinja


Yes, you need to do that. Not all functions put the null char for you, and strncpy, as I can read in its man page, requires to have a null byte among the first n characters of src.

like image 28
Adrián Pérez Avatar answered Sep 21 '22 00:09

Adrián Pérez