Search⌘ K
AI Features

Discussion: String Construction

Explore the critical role of string termination in C programming. Learn how to properly terminate extracted strings to prevent buffer overflow and incorrect output. This lesson helps you understand common pitfalls in string manipulation and ways to enhance your code's security and reliability.

Run the code

Now, it's time to execute the code and observe the output.

C++
#include <stdio.h>
int main()
{
char filename[] = "update.txt";
char name[16];
int x;
/* initialize the name[] buffer with dots */
for( x=0; x<16; x++ )
name[x] = '.';
/* extract first part of the filename */
x = 0;
while( filename[x] != '.' ) {
name[x] = filename[x];
x++;
}
/* output result */
printf("Extracted name '%.16s' from '%s'\n", name, filename);
return(0);
}

Understanding the output

The code extracts the first part of a filename, before the extension. But it fails:

Extracted name 'update..........' from 'update.txt'
Code output

String termination is crucial

This point is to drive home the importance of properly terminating strings you ...