Restricted vs Unrestricted String Function in C

This C Tutorial explains Unrestricted and Length-Restricted String Functions in C with examples.

Standard C library provides several string handling functions for performing various operations on strings. These functions are categorised into Length-Unrestricted and Length-Restricted functions. To use functions in a C program, include ‘‘ header which contains prototypes for both types of functions.

In general, Length-Unrestricted functions perform the specified operation like copy source string to destination, or concatenation of the source to the end of destination or to compare source and destination considering the full length of the source string. Let’s first focus on prototypes of functions,

    char *strcpy(char *dst, char const *src);
    /* strcpy copies 'src' to 'dst' */
    char *strcat(char *dst, char const *src);
    /* strcat concatenates 'src' to end of 'dst' */
    int strcmp(char const *str1, char const *str2);
    /* strcmp compares 'str1' and 'str2' */

Notice that strcpy and strcat functions return pointer to dst string while strcmp function returns an integer value.

In strcpy, if ‘src’ is longer than ‘dst’ array, it’ll copy ‘src’ into ‘dst’, overwrites whatever values happen to come after the ‘dst’ array in memory. Thus, overflowing the ‘dst’ array. Since, strcpy can’t determine if ‘dst’ array is long enough to hold the copy of ‘src’ string, it’s up to the programmer to ensure this. For ex.

/*
 * srcstr_longer_dststr.c -- program shows what happens when copying larger
 * 'src' str to shorter 'dst' str
 */
#include <string.h>	/* string functions prototype */
#include <stdio.h> 
 
int main(void)
{
    char *src = "Hello, strcpy.";	/* 'src' have 14 characters */
    char dst[5];			/* 'dst' has 5 char */
    char *copied;
 
    copied = strcpy(dst, src);
    printf("strcpy() returns \"%s\"\n", copied);
    return 0;
}

Output is below:

advertisement
advertisement
strcpy() returns "Hello, strcpy."

In case if ‘src’ string is shorter than ‘dst’ array, ‘src’ string is copied into ‘dst’ array and old contents of ‘dst’ array are overwritten and lost. Old contents of ‘dst’ after the 1st NULL byte aren’t accessible and therefore of no practical importance.

strcat appends ‘src’ string to the end of ‘dst’ array. Therefore, it requires ‘dst’ array to be, at least, (possibly) empty string in case if it doesn’t have any characters. It copies the ‘src’ string and appends to the end of ‘dst’ array and returns a pointer to ‘dst’ array. Again, it’s up to the programmer to ensure that remaining space in ‘dst’ array should be long enough to hold the ‘src’ string. If it’s not the case, strcat runs off the end of the ‘dst’ array and writes into variables whichever happen to come after the ‘dst’ array in memory.

Let’s see an example program,

/* 
 * strcat.c -- program shows what happens when appending 'src' str to 'dst'
 * str
 */
#include <stdio.h>
#include <string.h>
#define SIZE 25
 
int main(void)
{
    char src[SIZE];
    char quit[] = "quit";
    char dst[SIZE] = "";    /* empty string */
    char *cptr2dst;
 
    puts("\n****Program appends source string to destination array****\n");
    printf("User, type in a character string, this time not more than %d "
           "characters long...,\nor \"quit\" to quit the program.\n", SIZE);
    gets(src);
    while (strncmp("quit", src, 4)) {
        cptr2dst = strcat(dst, src);
 
        printf("\n\nDestination string becomes \"%s\"\n", cptr2dst);
        printf("And size, in bytes, of destination string is %d and %d "
               "bytes remaining.\n\n", strlen(dst), SIZE - strlen(dst));
 
        if (strlen(dst) > SIZE)
            puts("\a\"DST OVERFLOWN!\"\a");
 
        puts("\t\t\t***************\t\t\t\n");
 
        printf("Want to append destination further, type in a new string "
               not more than %d characters\nOr enter \"quit\" to terminate."
               "\n\n", SIZE - strlen(dst));
        gets(src);
    }
    puts("Bye! It's Interesting!\n");
    return 0;
}

Observe the output below:

****Program appends source string to destination array****
 
User, type in a character string, this time not more than 25 characters
long..., or "quit" to quit the program.
okey, how's
 
 
Destination string becomes "okey, how's"
And size, in bytes, of destination string is 11 and 14 bytes remaining.
 
			***************			
 
Want to append destination further, type in a new string not more than 14
characters Or enter "quit" to terminate.
 
 your      
 
 
Destination string becomes "okey, how's your"
And size, in bytes, of destination string is 16 and 9 bytes remaining.
 
			***************			
 
Want to append destination further, type in a new string not more than 9
characters Or enter "quit" to terminate.
 
 c prog
 
 
Destination string becomes "okey, how's your c prog"
And size, in bytes, of destination string is 23 and 2 bytes remaining.
 
			***************			
 
Want to append destination further, type in a new string not more than 2
characters Or enter "quit" to terminate.
 
ramming
 
 
Destination string becomes "okey, how's your c programming"
And size, in bytes, of destination string is 30 and -5 bytes remaining.
 
"DST OVERFLOWN!"
			***************			
 
Want to append destination further, type in a new string not more than -5
characters Or enter "quit" to terminate.
 
quit
Bye! It's Interesting!

Notice that strcat doesn’t care for if ‘dst’ has enough room for new string to be appended. It just appends and runs off the end of ‘dst’ writing into locations whatever be after the ‘dst’ in memory.

advertisement

Now, turn to strcmp function which compares two strings to their corresponding characters and return 0 if two are same or negative value if first string is lower than second or positive when second string is higher than first. Let’s take an example,

/*
 * strcmp.c -- program shows how two strings str1 and str2 compared and
 * return int value
 */
#include <stdio.h>
#include <string.h>
#define SIZE 5
 
int main(void)
{
    char str1[SIZE];
    char str2[SIZE];
    int ret;
 
    puts("\n*****Program compares two strings in full lengths*****\n");
    printf("Enter first string not more than %d characters or \"quit\" to "
           "Quit.\n", SIZE);
    gets(str1);
 
    while (strncmp("quit", str1, 4)) {
        printf("\nEnter second string not more than %d characters\n", SIZE);
        gets(str2);
 
        if ((ret = strcmp(str1, str2)) == 0)
            puts("\nTwo strings are SAME.");
        else if ((ret = strcmp(str1, str2)) < 0)
            puts("\nString first is Lower than second.");
        else
            puts("\nSecond string is Lower than first.");
 
        puts("\t\t\t*****************\t\t\t");
        printf("Want to continue...\nEnter first string not more than %d "
               "characters or \"quit\" to Quit.\n", SIZE);
        gets(str1);
    }
    printf("\nBye!\n");
    return 0;
}

Output as under:

*****Program compares two strings in full lengths*****
 
Enter first string not more than 5 characters or "quit" to Quit.
awake
 
Enter second string not more than 5 characters
drake
 
Strings first is Lower than second.
			*****************			
Want to continue...
Enter first string not more than 5 characters or "quit" to Quit.
mello
 
Enter second string not more than 5 characters
mello
 
Two strings are SAME.
			*****************			
Want to continue...
Enter first string not more than 5 characters or "quit" to Quit.
hello
 
Enter second string not more than 5 characters
zello 
 
Strings first is Lower than second.
			*****************			
Want to continue...
Enter first string not more than 5 characters or "quit" to Quit.
quit
 
Bye!

Let’s consider prototypes of Length-Restricted String functions,

advertisement
    char *strncpy(char *src, char const *dst, Size_t len);
    char *strncat(char *src, char const *dst, size_t len);
    int strncmp(char const *str1, char const *str2, size_t len );

strncpy copies ‘len’ bytes from ‘src’ to ‘dst’, strncat appends ‘len’ bytes from ‘src’ to the end of ‘dst’ and strncmp compares ‘len’ bytes of ‘str1’ and ‘str2’.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.