-
Notifications
You must be signed in to change notification settings - Fork 27
/
safe_strncpy.c
49 lines (33 loc) · 1.22 KB
/
safe_strncpy.c
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
/****************************************************************
*
* Purpose: Program to demonstrate the 'strncpy' function.
* Author: M J Leslie
* Date: 03-Feb-96
*
****************************************************************/
#include <string.h> /* strcpy */
#include <stdio.h>
void SafeCopy(char *Dest, int DestSize, char *Source);
int main()
{
char Text1[20]="Tracy Sorrell"; /* string buffer */
char Text2[10]="Martin"; /* string buffer */
printf (" Original string contents are: %s\n", Text2);
SafeCopy(Text2, sizeof(Text2), Text1);
printf (" New string contents are: %s\n", Text2);
strcpy(Text2, "Alex");
printf (" Final string contents are: %s\n", Text2);
}
/****************************************************************/
void SafeCopy(
char *Dest, /* Destination buffer. */
int DestSize,
char *Source) /* Source data. */
{
/* ... Copy 'Source' into 'Dest'.
* ... 'Dest' is padded with NULLs if 'Source' is smaller.. */
strncpy(Dest, Source, DestSize);
/* ... Safety net! Add the NULL just in case 'Source' is larger
* ... than 'Dest'. */
Dest[DestSize-1] = '\0';
}