-
Notifications
You must be signed in to change notification settings - Fork 3
/
string.texi
2669 lines (2225 loc) · 105 KB
/
string.texi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@node String and Array Utilities, Character Set Handling, Character Handling, Top
@c %MENU% Utilities for copying and comparing strings and arrays
@chapter String and Array Utilities
Operations on strings (or arrays of characters) are an important part of
many programs. The GNU C library provides an extensive set of string
utility functions, including functions for copying, concatenating,
comparing, and searching strings. Many of these functions can also
operate on arbitrary regions of storage; for example, the @code{memcpy}
function can be used to copy the contents of any kind of array.
It's fairly common for beginning C programmers to ``reinvent the wheel''
by duplicating this functionality in their own code, but it pays to
become familiar with the library functions and to make use of them,
since this offers benefits in maintenance, efficiency, and portability.
For instance, you could easily compare one string to another in two
lines of C code, but if you use the built-in @code{strcmp} function,
you're less likely to make a mistake. And, since these library
functions are typically highly optimized, your program may run faster
too.
@menu
* Representation of Strings:: Introduction to basic concepts.
* String/Array Conventions:: Whether to use a string function or an
arbitrary array function.
* String Length:: Determining the length of a string.
* Copying and Concatenation:: Functions to copy the contents of strings
and arrays.
* String/Array Comparison:: Functions for byte-wise and character-wise
comparison.
* Collation Functions:: Functions for collating strings.
* Search Functions:: Searching for a specific element or substring.
* Finding Tokens in a String:: Splitting a string into tokens by looking
for delimiters.
* strfry:: Function for flash-cooking a string.
* Trivial Encryption:: Obscuring data.
* Encode Binary Data:: Encoding and Decoding of Binary Data.
* Argz and Envz Vectors:: Null-separated string vectors.
@end menu
@node Representation of Strings
@section Representation of Strings
@cindex string, representation of
This section is a quick summary of string concepts for beginning C
programmers. It describes how character strings are represented in C
and some common pitfalls. If you are already familiar with this
material, you can skip this section.
@cindex string
@cindex multibyte character string
A @dfn{string} is an array of @code{char} objects. But string-valued
variables are usually declared to be pointers of type @code{char *}.
Such variables do not include space for the text of a string; that has
to be stored somewhere else---in an array variable, a string constant,
or dynamically allocated memory (@pxref{Memory Allocation}). It's up to
you to store the address of the chosen memory space into the pointer
variable. Alternatively you can store a @dfn{null pointer} in the
pointer variable. The null pointer does not point anywhere, so
attempting to reference the string it points to gets an error.
@cindex wide character string
``string'' normally refers to multibyte character strings as opposed to
wide character strings. Wide character strings are arrays of type
@code{wchar_t} and as for multibyte character strings usually pointers
of type @code{wchar_t *} are used.
@cindex null character
@cindex null wide character
By convention, a @dfn{null character}, @code{'\0'}, marks the end of a
multibyte character string and the @dfn{null wide character},
@code{L'\0'}, marks the end of a wide character string. For example, in
testing to see whether the @code{char *} variable @var{p} points to a
null character marking the end of a string, you can write
@code{!*@var{p}} or @code{*@var{p} == '\0'}.
A null character is quite different conceptually from a null pointer,
although both are represented by the integer @code{0}.
@cindex string literal
@dfn{String literals} appear in C program source as strings of
characters between double-quote characters (@samp{"}) where the initial
double-quote character is immediately preceded by a capital @samp{L}
(ell) character (as in @code{L"foo"}). In @w{ISO C}, string literals
can also be formed by @dfn{string concatenation}: @code{"a" "b"} is the
same as @code{"ab"}. For wide character strings one can either use
@code{L"a" L"b"} or @code{L"a" "b"}. Modification of string literals is
not allowed by the GNU C compiler, because literals are placed in
read-only storage.
Character arrays that are declared @code{const} cannot be modified
either. It's generally good style to declare non-modifiable string
pointers to be of type @code{const char *}, since this often allows the
C compiler to detect accidental modifications as well as providing some
amount of documentation about what your program intends to do with the
string.
The amount of memory allocated for the character array may extend past
the null character that normally marks the end of the string. In this
document, the term @dfn{allocated size} is always used to refer to the
total amount of memory allocated for the string, while the term
@dfn{length} refers to the number of characters up to (but not
including) the terminating null character.
@cindex length of string
@cindex allocation size of string
@cindex size of string
@cindex string length
@cindex string allocation
A notorious source of program bugs is trying to put more characters in a
string than fit in its allocated size. When writing code that extends
strings or moves characters into a pre-allocated array, you should be
very careful to keep track of the length of the text and make explicit
checks for overflowing the array. Many of the library functions
@emph{do not} do this for you! Remember also that you need to allocate
an extra byte to hold the null character that marks the end of the
string.
@cindex single-byte string
@cindex multibyte string
Originally strings were sequences of bytes where each byte represents a
single character. This is still true today if the strings are encoded
using a single-byte character encoding. Things are different if the
strings are encoded using a multibyte encoding (for more information on
encodings see @ref{Extended Char Intro}). There is no difference in
the programming interface for these two kind of strings; the programmer
has to be aware of this and interpret the byte sequences accordingly.
But since there is no separate interface taking care of these
differences the byte-based string functions are sometimes hard to use.
Since the count parameters of these functions specify bytes a call to
@code{strncpy} could cut a multibyte character in the middle and put an
incomplete (and therefore unusable) byte sequence in the target buffer.
@cindex wide character string
To avoid these problems later versions of the @w{ISO C} standard
introduce a second set of functions which are operating on @dfn{wide
characters} (@pxref{Extended Char Intro}). These functions don't have
the problems the single-byte versions have since every wide character is
a legal, interpretable value. This does not mean that cutting wide
character strings at arbitrary points is without problems. It normally
is for alphabet-based languages (except for non-normalized text) but
languages based on syllables still have the problem that more than one
wide character is necessary to complete a logical unit. This is a
higher level problem which the @w{C library} functions are not designed
to solve. But it is at least good that no invalid byte sequences can be
created. Also, the higher level functions can also much easier operate
on wide character than on multibyte characters so that a general advise
is to use wide characters internally whenever text is more than simply
copied.
The remaining of this chapter will discuss the functions for handling
wide character strings in parallel with the discussion of the multibyte
character strings since there is almost always an exact equivalent
available.
@node String/Array Conventions
@section String and Array Conventions
This chapter describes both functions that work on arbitrary arrays or
blocks of memory, and functions that are specific to null-terminated
arrays of characters and wide characters.
Functions that operate on arbitrary blocks of memory have names
beginning with @samp{mem} and @samp{wmem} (such as @code{memcpy} and
@code{wmemcpy}) and invariably take an argument which specifies the size
(in bytes and wide characters respectively) of the block of memory to
operate on. The array arguments and return values for these functions
have type @code{void *} or @code{wchar_t}. As a matter of style, the
elements of the arrays used with the @samp{mem} functions are referred
to as ``bytes''. You can pass any kind of pointer to these functions,
and the @code{sizeof} operator is useful in computing the value for the
size argument. Parameters to the @samp{wmem} functions must be of type
@code{wchar_t *}. These functions are not really usable with anything
but arrays of this type.
In contrast, functions that operate specifically on strings and wide
character strings have names beginning with @samp{str} and @samp{wcs}
respectively (such as @code{strcpy} and @code{wcscpy}) and look for a
null character to terminate the string instead of requiring an explicit
size argument to be passed. (Some of these functions accept a specified
maximum length, but they also check for premature termination with a
null character.) The array arguments and return values for these
functions have type @code{char *} and @code{wchar_t *} respectively, and
the array elements are referred to as ``characters'' and ``wide
characters''.
In many cases, there are both @samp{mem} and @samp{str}/@samp{wcs}
versions of a function. The one that is more appropriate to use depends
on the exact situation. When your program is manipulating arbitrary
arrays or blocks of storage, then you should always use the @samp{mem}
functions. On the other hand, when you are manipulating null-terminated
strings it is usually more convenient to use the @samp{str}/@samp{wcs}
functions, unless you already know the length of the string in advance.
The @samp{wmem} functions should be used for wide character arrays with
known size.
@cindex wint_t
@cindex parameter promotion
Some of the memory and string functions take single characters as
arguments. Since a value of type @code{char} is automatically promoted
into an value of type @code{int} when used as a parameter, the functions
are declared with @code{int} as the type of the parameter in question.
In case of the wide character function the situation is similarly: the
parameter type for a single wide character is @code{wint_t} and not
@code{wchar_t}. This would for many implementations not be necessary
since the @code{wchar_t} is large enough to not be automatically
promoted, but since the @w{ISO C} standard does not require such a
choice of types the @code{wint_t} type is used.
@node String Length
@section String Length
You can get the length of a string using the @code{strlen} function.
This function is declared in the header file @file{string.h}.
@pindex string.h
@comment string.h
@comment ISO
@deftypefun size_t strlen (const char *@var{s})
The @code{strlen} function returns the length of the null-terminated
string @var{s} in bytes. (In other words, it returns the offset of the
terminating null character within the array.)
For example,
@smallexample
strlen ("hello, world")
@result{} 12
@end smallexample
When applied to a character array, the @code{strlen} function returns
the length of the string stored there, not its allocated size. You can
get the allocated size of the character array that holds a string using
the @code{sizeof} operator:
@smallexample
char string[32] = "hello, world";
sizeof (string)
@result{} 32
strlen (string)
@result{} 12
@end smallexample
But beware, this will not work unless @var{string} is the character
array itself, not a pointer to it. For example:
@smallexample
char string[32] = "hello, world";
char *ptr = string;
sizeof (string)
@result{} 32
sizeof (ptr)
@result{} 4 /* @r{(on a machine with 4 byte pointers)} */
@end smallexample
This is an easy mistake to make when you are working with functions that
take string arguments; those arguments are always pointers, not arrays.
It must also be noted that for multibyte encoded strings the return
value does not have to correspond to the number of characters in the
string. To get this value the string can be converted to wide
characters and @code{wcslen} can be used or something like the following
code can be used:
@smallexample
/* @r{The input is in @code{string}.}
@r{The length is expected in @code{n}.} */
@{
mbstate_t t;
char *scopy = string;
/* In initial state. */
memset (&t, '\0', sizeof (t));
/* Determine number of characters. */
n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);
@}
@end smallexample
This is cumbersome to do so if the number of characters (as opposed to
bytes) is needed often it is better to work with wide characters.
@end deftypefun
The wide character equivalent is declared in @file{wchar.h}.
@comment wchar.h
@comment ISO
@deftypefun size_t wcslen (const wchar_t *@var{ws})
The @code{wcslen} function is the wide character equivalent to
@code{strlen}. The return value is the number of wide characters in the
wide character string pointed to by @var{ws} (this is also the offset of
the terminating null wide character of @var{ws}).
Since there are no multi wide character sequences making up one
character the return value is not only the offset in the array, it is
also the number of wide characters.
This function was introduced in @w{Amendment 1} to @w{ISO C90}.
@end deftypefun
@comment string.h
@comment GNU
@deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
The @code{strnlen} function returns the length of the string @var{s} in
bytes if this length is smaller than @var{maxlen} bytes. Otherwise it
returns @var{maxlen}. Therefore this function is equivalent to
@code{(strlen (@var{s}) < n ? strlen (@var{s}) : @var{maxlen})} but it
is more efficient and works even if the string @var{s} is not
null-terminated.
@smallexample
char string[32] = "hello, world";
strnlen (string, 32)
@result{} 12
strnlen (string, 5)
@result{} 5
@end smallexample
This function is a GNU extension and is declared in @file{string.h}.
@end deftypefun
@comment wchar.h
@comment GNU
@deftypefun size_t wcsnlen (const wchar_t *@var{ws}, size_t @var{maxlen})
@code{wcsnlen} is the wide character equivalent to @code{strnlen}. The
@var{maxlen} parameter specifies the maximum number of wide characters.
This function is a GNU extension and is declared in @file{wchar.h}.
@end deftypefun
@node Copying and Concatenation
@section Copying and Concatenation
You can use the functions described in this section to copy the contents
of strings and arrays, or to append the contents of one string to
another. The @samp{str} and @samp{mem} functions are declared in the
header file @file{string.h} while the @samp{wstr} and @samp{wmem}
functions are declared in the file @file{wchar.h}.
@pindex string.h
@pindex wchar.h
@cindex copying strings and arrays
@cindex string copy functions
@cindex array copy functions
@cindex concatenating strings
@cindex string concatenation functions
A helpful way to remember the ordering of the arguments to the functions
in this section is that it corresponds to an assignment expression, with
the destination array specified to the left of the source array. All
of these functions return the address of the destination array.
Most of these functions do not work properly if the source and
destination arrays overlap. For example, if the beginning of the
destination array overlaps the end of the source array, the original
contents of that part of the source array may get overwritten before it
is copied. Even worse, in the case of the string functions, the null
character marking the end of the string may be lost, and the copy
function might get stuck in a loop trashing all the memory allocated to
your program.
All functions that have problems copying between overlapping arrays are
explicitly identified in this manual. In addition to functions in this
section, there are a few others like @code{sprintf} (@pxref{Formatted
Output Functions}) and @code{scanf} (@pxref{Formatted Input
Functions}).
@comment string.h
@comment ISO
@deftypefun {void *} memcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
The @code{memcpy} function copies @var{size} bytes from the object
beginning at @var{from} into the object beginning at @var{to}. The
behavior of this function is undefined if the two arrays @var{to} and
@var{from} overlap; use @code{memmove} instead if overlapping is possible.
The value returned by @code{memcpy} is the value of @var{to}.
Here is an example of how you might use @code{memcpy} to copy the
contents of an array:
@smallexample
struct foo *oldarray, *newarray;
int arraysize;
@dots{}
memcpy (new, old, arraysize * sizeof (struct foo));
@end smallexample
@end deftypefun
@comment wchar.h
@comment ISO
@deftypefun {wchar_t *} wmemcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
The @code{wmemcpy} function copies @var{size} wide characters from the object
beginning at @var{wfrom} into the object beginning at @var{wto}. The
behavior of this function is undefined if the two arrays @var{wto} and
@var{wfrom} overlap; use @code{wmemmove} instead if overlapping is possible.
The following is a possible implementation of @code{wmemcpy} but there
are more optimizations possible.
@smallexample
wchar_t *
wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
size_t size)
@{
return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
@}
@end smallexample
The value returned by @code{wmemcpy} is the value of @var{wto}.
This function was introduced in @w{Amendment 1} to @w{ISO C90}.
@end deftypefun
@comment string.h
@comment GNU
@deftypefun {void *} mempcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
The @code{mempcpy} function is nearly identical to the @code{memcpy}
function. It copies @var{size} bytes from the object beginning at
@code{from} into the object pointed to by @var{to}. But instead of
returning the value of @var{to} it returns a pointer to the byte
following the last written byte in the object beginning at @var{to}.
I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
This function is useful in situations where a number of objects shall be
copied to consecutive memory positions.
@smallexample
void *
combine (void *o1, size_t s1, void *o2, size_t s2)
@{
void *result = malloc (s1 + s2);
if (result != NULL)
mempcpy (mempcpy (result, o1, s1), o2, s2);
return result;
@}
@end smallexample
This function is a GNU extension.
@end deftypefun
@comment wchar.h
@comment GNU
@deftypefun {wchar_t *} wmempcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
The @code{wmempcpy} function is nearly identical to the @code{wmemcpy}
function. It copies @var{size} wide characters from the object
beginning at @code{wfrom} into the object pointed to by @var{wto}. But
instead of returning the value of @var{wto} it returns a pointer to the
wide character following the last written wide character in the object
beginning at @var{wto}. I.e., the value is @code{@var{wto} + @var{size}}.
This function is useful in situations where a number of objects shall be
copied to consecutive memory positions.
The following is a possible implementation of @code{wmemcpy} but there
are more optimizations possible.
@smallexample
wchar_t *
wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
size_t size)
@{
return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
@}
@end smallexample
This function is a GNU extension.
@end deftypefun
@comment string.h
@comment ISO
@deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
@code{memmove} copies the @var{size} bytes at @var{from} into the
@var{size} bytes at @var{to}, even if those two blocks of space
overlap. In the case of overlap, @code{memmove} is careful to copy the
original values of the bytes in the block at @var{from}, including those
bytes which also belong to the block at @var{to}.
The value returned by @code{memmove} is the value of @var{to}.
@end deftypefun
@comment wchar.h
@comment ISO
@deftypefun {wchar_t *} wmemmove (wchar *@var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
@code{wmemmove} copies the @var{size} wide characters at @var{wfrom}
into the @var{size} wide characters at @var{wto}, even if those two
blocks of space overlap. In the case of overlap, @code{memmove} is
careful to copy the original values of the wide characters in the block
at @var{wfrom}, including those wide characters which also belong to the
block at @var{wto}.
The following is a possible implementation of @code{wmemcpy} but there
are more optimizations possible.
@smallexample
wchar_t *
wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
size_t size)
@{
return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
@}
@end smallexample
The value returned by @code{wmemmove} is the value of @var{wto}.
This function is a GNU extension.
@end deftypefun
@comment string.h
@comment SVID
@deftypefun {void *} memccpy (void *restrict @var{to}, const void *restrict @var{from}, int @var{c}, size_t @var{size})
This function copies no more than @var{size} bytes from @var{from} to
@var{to}, stopping if a byte matching @var{c} is found. The return
value is a pointer into @var{to} one byte past where @var{c} was copied,
or a null pointer if no byte matching @var{c} appeared in the first
@var{size} bytes of @var{from}.
@end deftypefun
@comment string.h
@comment ISO
@deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
This function copies the value of @var{c} (converted to an
@code{unsigned char}) into each of the first @var{size} bytes of the
object beginning at @var{block}. It returns the value of @var{block}.
@end deftypefun
@comment wchar.h
@comment ISO
@deftypefun {wchar_t *} wmemset (wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
This function copies the value of @var{wc} into each of the first
@var{size} wide characters of the object beginning at @var{block}. It
returns the value of @var{block}.
@end deftypefun
@comment string.h
@comment ISO
@deftypefun {char *} strcpy (char *restrict @var{to}, const char *restrict @var{from})
This copies characters from the string @var{from} (up to and including
the terminating null character) into the string @var{to}. Like
@code{memcpy}, this function has undefined results if the strings
overlap. The return value is the value of @var{to}.
@end deftypefun
@comment wchar.h
@comment ISO
@deftypefun {wchar_t *} wcscpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
This copies wide characters from the string @var{wfrom} (up to and
including the terminating null wide character) into the string
@var{wto}. Like @code{wmemcpy}, this function has undefined results if
the strings overlap. The return value is the value of @var{wto}.
@end deftypefun
@comment string.h
@comment ISO
@deftypefun {char *} strncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
This function is similar to @code{strcpy} but always copies exactly
@var{size} characters into @var{to}.
If the length of @var{from} is more than @var{size}, then @code{strncpy}
copies just the first @var{size} characters. Note that in this case
there is no null terminator written into @var{to}.
If the length of @var{from} is less than @var{size}, then @code{strncpy}
copies all of @var{from}, followed by enough null characters to add up
to @var{size} characters in all. This behavior is rarely useful, but it
is specified by the @w{ISO C} standard.
The behavior of @code{strncpy} is undefined if the strings overlap.
Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
relating to writing past the end of the allocated space for @var{to}.
However, it can also make your program much slower in one common case:
copying a string which is probably small into a potentially large buffer.
In this case, @var{size} may be large, and when it is, @code{strncpy} will
waste a considerable amount of time copying null characters.
@end deftypefun
@comment wchar.h
@comment ISO
@deftypefun {wchar_t *} wcsncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
This function is similar to @code{wcscpy} but always copies exactly
@var{size} wide characters into @var{wto}.
If the length of @var{wfrom} is more than @var{size}, then
@code{wcsncpy} copies just the first @var{size} wide characters. Note
that in this case there is no null terminator written into @var{wto}.
If the length of @var{wfrom} is less than @var{size}, then
@code{wcsncpy} copies all of @var{wfrom}, followed by enough null wide
characters to add up to @var{size} wide characters in all. This
behavior is rarely useful, but it is specified by the @w{ISO C}
standard.
The behavior of @code{wcsncpy} is undefined if the strings overlap.
Using @code{wcsncpy} as opposed to @code{wcscpy} is a way to avoid bugs
relating to writing past the end of the allocated space for @var{wto}.
However, it can also make your program much slower in one common case:
copying a string which is probably small into a potentially large buffer.
In this case, @var{size} may be large, and when it is, @code{wcsncpy} will
waste a considerable amount of time copying null wide characters.
@end deftypefun
@comment string.h
@comment SVID
@deftypefun {char *} strdup (const char *@var{s})
This function copies the null-terminated string @var{s} into a newly
allocated string. The string is allocated using @code{malloc}; see
@ref{Unconstrained Allocation}. If @code{malloc} cannot allocate space
for the new string, @code{strdup} returns a null pointer. Otherwise it
returns a pointer to the new string.
@end deftypefun
@comment wchar.h
@comment GNU
@deftypefun {wchar_t *} wcsdup (const wchar_t *@var{ws})
This function copies the null-terminated wide character string @var{ws}
into a newly allocated string. The string is allocated using
@code{malloc}; see @ref{Unconstrained Allocation}. If @code{malloc}
cannot allocate space for the new string, @code{wcsdup} returns a null
pointer. Otherwise it returns a pointer to the new wide character
string.
This function is a GNU extension.
@end deftypefun
@comment string.h
@comment GNU
@deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
This function is similar to @code{strdup} but always copies at most
@var{size} characters into the newly allocated string.
If the length of @var{s} is more than @var{size}, then @code{strndup}
copies just the first @var{size} characters and adds a closing null
terminator. Otherwise all characters are copied and the string is
terminated.
This function is different to @code{strncpy} in that it always
terminates the destination string.
@code{strndup} is a GNU extension.
@end deftypefun
@comment string.h
@comment Unknown origin
@deftypefun {char *} stpcpy (char *restrict @var{to}, const char *restrict @var{from})
This function is like @code{strcpy}, except that it returns a pointer to
the end of the string @var{to} (that is, the address of the terminating
null character @code{to + strlen (from)}) rather than the beginning.
For example, this program uses @code{stpcpy} to concatenate @samp{foo}
and @samp{bar} to produce @samp{foobar}, which it then prints.
@smallexample
@include stpcpy.c.texi
@end smallexample
This function is not part of the ISO or POSIX standards, and is not
customary on Unix systems, but we did not invent it either. Perhaps it
comes from MS-DOG.
Its behavior is undefined if the strings overlap. The function is
declared in @file{string.h}.
@end deftypefun
@comment wchar.h
@comment GNU
@deftypefun {wchar_t *} wcpcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
This function is like @code{wcscpy}, except that it returns a pointer to
the end of the string @var{wto} (that is, the address of the terminating
null character @code{wto + strlen (wfrom)}) rather than the beginning.
This function is not part of ISO or POSIX but was found useful while
developing the GNU C Library itself.
The behavior of @code{wcpcpy} is undefined if the strings overlap.
@code{wcpcpy} is a GNU extension and is declared in @file{wchar.h}.
@end deftypefun
@comment string.h
@comment GNU
@deftypefun {char *} stpncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
This function is similar to @code{stpcpy} but copies always exactly
@var{size} characters into @var{to}.
If the length of @var{from} is more then @var{size}, then @code{stpncpy}
copies just the first @var{size} characters and returns a pointer to the
character directly following the one which was copied last. Note that in
this case there is no null terminator written into @var{to}.
If the length of @var{from} is less than @var{size}, then @code{stpncpy}
copies all of @var{from}, followed by enough null characters to add up
to @var{size} characters in all. This behavior is rarely useful, but it
is implemented to be useful in contexts where this behavior of the
@code{strncpy} is used. @code{stpncpy} returns a pointer to the
@emph{first} written null character.
This function is not part of ISO or POSIX but was found useful while
developing the GNU C Library itself.
Its behavior is undefined if the strings overlap. The function is
declared in @file{string.h}.
@end deftypefun
@comment wchar.h
@comment GNU
@deftypefun {wchar_t *} wcpncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
This function is similar to @code{wcpcpy} but copies always exactly
@var{wsize} characters into @var{wto}.
If the length of @var{wfrom} is more then @var{size}, then
@code{wcpncpy} copies just the first @var{size} wide characters and
returns a pointer to the wide character directly following the last
non-null wide character which was copied last. Note that in this case
there is no null terminator written into @var{wto}.
If the length of @var{wfrom} is less than @var{size}, then @code{wcpncpy}
copies all of @var{wfrom}, followed by enough null characters to add up
to @var{size} characters in all. This behavior is rarely useful, but it
is implemented to be useful in contexts where this behavior of the
@code{wcsncpy} is used. @code{wcpncpy} returns a pointer to the
@emph{first} written null character.
This function is not part of ISO or POSIX but was found useful while
developing the GNU C Library itself.
Its behavior is undefined if the strings overlap.
@code{wcpncpy} is a GNU extension and is declared in @file{wchar.h}.
@end deftypefun
@comment string.h
@comment GNU
@deftypefn {Macro} {char *} strdupa (const char *@var{s})
This macro is similar to @code{strdup} but allocates the new string
using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
Automatic}). This means of course the returned string has the same
limitations as any block of memory allocated using @code{alloca}.
For obvious reasons @code{strdupa} is implemented only as a macro;
you cannot get the address of this function. Despite this limitation
it is a useful function. The following code shows a situation where
using @code{malloc} would be a lot more expensive.
@smallexample
@include strdupa.c.texi
@end smallexample
Please note that calling @code{strtok} using @var{path} directly is
invalid. It is also not allowed to call @code{strdupa} in the argument
list of @code{strtok} since @code{strdupa} uses @code{alloca}
(@pxref{Variable Size Automatic}) can interfere with the parameter
passing.
This function is only available if GNU CC is used.
@end deftypefn
@comment string.h
@comment GNU
@deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
This function is similar to @code{strndup} but like @code{strdupa} it
allocates the new string using @code{alloca}
@pxref{Variable Size Automatic}. The same advantages and limitations
of @code{strdupa} are valid for @code{strndupa}, too.
This function is implemented only as a macro, just like @code{strdupa}.
Just as @code{strdupa} this macro also must not be used inside the
parameter list in a function call.
@code{strndupa} is only available if GNU CC is used.
@end deftypefn
@comment string.h
@comment ISO
@deftypefun {char *} strcat (char *restrict @var{to}, const char *restrict @var{from})
The @code{strcat} function is similar to @code{strcpy}, except that the
characters from @var{from} are concatenated or appended to the end of
@var{to}, instead of overwriting it. That is, the first character from
@var{from} overwrites the null character marking the end of @var{to}.
An equivalent definition for @code{strcat} would be:
@smallexample
char *
strcat (char *restrict to, const char *restrict from)
@{
strcpy (to + strlen (to), from);
return to;
@}
@end smallexample
This function has undefined results if the strings overlap.
@end deftypefun
@comment wchar.h
@comment ISO
@deftypefun {wchar_t *} wcscat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
The @code{wcscat} function is similar to @code{wcscpy}, except that the
characters from @var{wfrom} are concatenated or appended to the end of
@var{wto}, instead of overwriting it. That is, the first character from
@var{wfrom} overwrites the null character marking the end of @var{wto}.
An equivalent definition for @code{wcscat} would be:
@smallexample
wchar_t *
wcscat (wchar_t *wto, const wchar_t *wfrom)
@{
wcscpy (wto + wcslen (wto), wfrom);
return wto;
@}
@end smallexample
This function has undefined results if the strings overlap.
@end deftypefun
Programmers using the @code{strcat} or @code{wcscat} function (or the
following @code{strncat} or @code{wcsncar} functions for that matter)
can easily be recognized as lazy and reckless. In almost all situations
the lengths of the participating strings are known (it better should be
since how can one otherwise ensure the allocated size of the buffer is
sufficient?) Or at least, one could know them if one keeps track of the
results of the various function calls. But then it is very inefficient
to use @code{strcat}/@code{wcscat}. A lot of time is wasted finding the
end of the destination string so that the actual copying can start.
This is a common example:
@cindex __va_copy
@cindex va_copy
@smallexample
/* @r{This function concatenates arbitrarily many strings. The last}
@r{parameter must be @code{NULL}.} */
char *
concat (const char *str, @dots{})
@{
va_list ap, ap2;
size_t total = 1;
const char *s;
char *result;
va_start (ap, str);
/* @r{Actually @code{va_copy}, but this is the name more gcc versions}
@r{understand.} */
__va_copy (ap2, ap);
/* @r{Determine how much space we need.} */
for (s = str; s != NULL; s = va_arg (ap, const char *))
total += strlen (s);
va_end (ap);
result = (char *) malloc (total);
if (result != NULL)
@{
result[0] = '\0';
/* @r{Copy the strings.} */
for (s = str; s != NULL; s = va_arg (ap2, const char *))
strcat (result, s);
@}
va_end (ap2);
return result;
@}
@end smallexample
This looks quite simple, especially the second loop where the strings
are actually copied. But these innocent lines hide a major performance
penalty. Just imagine that ten strings of 100 bytes each have to be
concatenated. For the second string we search the already stored 100
bytes for the end of the string so that we can append the next string.
For all strings in total the comparisons necessary to find the end of
the intermediate results sums up to 5500! If we combine the copying
with the search for the allocation we can write this function more
efficient:
@smallexample
char *
concat (const char *str, @dots{})
@{
va_list ap;
size_t allocated = 100;
char *result = (char *) malloc (allocated);
if (result != NULL)
@{
char *newp;
char *wp;
va_start (ap, str);
wp = result;
for (s = str; s != NULL; s = va_arg (ap, const char *))
@{
size_t len = strlen (s);
/* @r{Resize the allocated memory if necessary.} */
if (wp + len + 1 > result + allocated)
@{
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
@{
free (result);
return NULL;
@}
wp = newp + (wp - result);
result = newp;
@}
wp = mempcpy (wp, s, len);
@}
/* @r{Terminate the result string.} */
*wp++ = '\0';
/* @r{Resize memory to the optimal size.} */
newp = realloc (result, wp - result);
if (newp != NULL)
result = newp;
va_end (ap);
@}
return result;
@}
@end smallexample
With a bit more knowledge about the input strings one could fine-tune
the memory allocation. The difference we are pointing to here is that
we don't use @code{strcat} anymore. We always keep track of the length
of the current intermediate result so we can safe us the search for the
end of the string and use @code{mempcpy}. Please note that we also
don't use @code{stpcpy} which might seem more natural since we handle
with strings. But this is not necessary since we already know the
length of the string and therefore can use the faster memory copying
function. The example would work for wide characters the same way.
Whenever a programmer feels the need to use @code{strcat} she or he
should think twice and look through the program whether the code cannot
be rewritten to take advantage of already calculated results. Again: it
is almost always unnecessary to use @code{strcat}.
@comment string.h
@comment ISO
@deftypefun {char *} strncat (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
This function is like @code{strcat} except that not more than @var{size}
characters from @var{from} are appended to the end of @var{to}. A
single null character is also always appended to @var{to}, so the total
allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
longer than its initial length.
The @code{strncat} function could be implemented like this:
@smallexample
@group
char *
strncat (char *to, const char *from, size_t size)
@{
to[strlen (to) + size] = '\0';
strncpy (to + strlen (to), from, size);
return to;
@}
@end group
@end smallexample
The behavior of @code{strncat} is undefined if the strings overlap.
@end deftypefun
@comment wchar.h
@comment ISO
@deftypefun {wchar_t *} wcsncat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
This function is like @code{wcscat} except that not more than @var{size}
characters from @var{from} are appended to the end of @var{to}. A
single null character is also always appended to @var{to}, so the total
allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
longer than its initial length.
The @code{wcsncat} function could be implemented like this:
@smallexample
@group
wchar_t *
wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
size_t size)
@{
wto[wcslen (to) + size] = L'\0';
wcsncpy (wto + wcslen (wto), wfrom, size);
return wto;
@}
@end group
@end smallexample
The behavior of @code{wcsncat} is undefined if the strings overlap.
@end deftypefun
Here is an example showing the use of @code{strncpy} and @code{strncat}
(the wide character version is equivalent). Notice how, in the call to
@code{strncat}, the @var{size} parameter is computed to avoid
overflowing the character array @code{buffer}.