{"id":2801,"date":"2017-12-02T00:01:51","date_gmt":"2017-12-02T08:01:51","guid":{"rendered":"http:\/\/c-for-dummies.com\/blog\/?p=2801"},"modified":"2017-12-09T08:07:03","modified_gmt":"2017-12-09T16:07:03","slug":"safe-coding-practices-string-handling-2","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=2801","title":{"rendered":"Safe Coding Practices &#8211; String Handling 2"},"content":{"rendered":"<p>As with the <em>strcpy()<\/em> function, covered in <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=2816\">last week&#8217;s Lesson<\/a>, you run a risk of buffer overflow with <em>strcat()<\/em>. The compiler doesn&#8217;t check for an overflow; to ensure that you&#8217;re practicing <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=2797\">safe coding habits<\/a>, that task is up to you.<br \/>\n<!--more--><br \/>\nThe <em>strcat()<\/em> function sticks one string onto the end of another, a <em>concatenation<\/em> in geek-speak. You must ensure that enough room is available in the first string&#8217;s buffer to handle the length of the second string.<\/p>\n<p>I could show you the bad example first, instead the following code demonstrates one effective way to handle concatenation that ensures the buffers don&#8217;t overflow.<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;string.h&gt;\r\n\r\nint main()\r\n{\r\n    char input[32];\r\n    char *result;\r\n\r\n    <span class=\"comments\">\/* get first string *\/<\/span>\r\n    printf(\"Secret code: \");\r\n    fgets(input,32,stdin);\r\n\r\n    <span class=\"comments\">\/* create buffer and copy *\/<\/span>\r\n    result = (char *)malloc( strlen(input) + 1);\r\n    if(!result)\r\n    {\r\n        puts(\"Memory allocation error\");\r\n        exit(1);\r\n    }\r\n    strcpy(result,input);\r\n\r\n    <span class=\"comments\">\/* get second string *\/<\/span>\r\n    printf(\"Confirmation: \");\r\n    fgets(input,32,stdin);\r\n\r\n    <span class=\"comments\">\/* append to buffer *\/<\/span>\r\n    result = (char *)realloc(result,strlen(result)+strlen(input)+1);\r\n    if(!result)\r\n    {\r\n        puts(\"Memory allocation error\");\r\n        exit(1);\r\n    }\r\n    strcat(result,input);\r\n\r\n    printf(\"Resulting string below\\n%s\\n\",\r\n            result);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The first safe coding practice is to use the <em>fgets()<\/em> function to fetch the string. The <em>size<\/em> argument in <em>fgets()<\/em> is identical to the <code>input[]<\/code> buffer size; <em>fgets()<\/em> stops input at one less than its size value or whenever a newline (<code>'\\n'<\/code>) or <code>EOF<\/code> is encountered.<\/p>\n<p>At Line 15, the <em>malloc()<\/em> function allocates enough storage for the string <code>input<\/code>. Upon success, that location is assigned to the <code>result<\/code> pointer. The string is then copied from the <code>input<\/code> buffer to the <code>result<\/code> buffer at Line 21.<\/p>\n<p>Line 25 uses the <code>input<\/code> buffer again to fetch the second string. This approach is valid as any new content replaces the existing content in the <code>input<\/code> buffer; if nothing is input, the buffer holds a single null character (<code>'\\0'<\/code>).<\/p>\n<p>At Line 28, the <em>realloc()<\/em> function attempts to resize the <code>result<\/code> buffer. The new size is calculated based on the length of the string currently in the <code>result<\/code> buffer, plus the new string in the <code>input<\/code> buffer, plus one for a null character. Upon success, the <em>strcat()<\/em> function (Line 34) appends the string in <code>input<\/code> to the string in <code>result<\/code>.<\/p>\n<p>Whether you use <em>malloc()<\/em> or <em>realloc()<\/em> any of the other applicable <em>*alloc()<\/em> functions, the goal is the same: Ensure that the buffer has adequate storage to handle all characters in the final string. That way, you don&#8217;t risk a buffer overflow when using the <em>strcat()<\/em> function. You must, however, use a buffer to collect input, which is the <code>input[]<\/code> array in this example.<\/p>\n<p>If you&#8217;re dealing with string constants in your code, or you know the maximum allowed storage for a string, you can use static buffer sizes that provide plenty of wiggle room. That&#8217;s okay, assuming that you monitor the strings&#8217; lengths diligently, but if you&#8217;re truly after safe coding practices, allocate the storage as the program runs.<br \/>\n<a href=\"http:\/\/c-for-dummies.com\/blog\/?p=2834\">Next week&#8217;s Lesson<\/a> covers a third aspect of string booboos, which are manually-created strings that lack a termination character.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Buffer overflow occurs magically when working with strings, unless you&#8217;re very careful. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=2801\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-2801","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/2801","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2801"}],"version-history":[{"count":6,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/2801\/revisions"}],"predecessor-version":[{"id":2868,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/2801\/revisions\/2868"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2801"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2801"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2801"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}