Home > Enterprise >  How do I prevent string overflow in C?
How do I prevent string overflow in C?

Time:11-25

I'm trying to make a program which concatenates two strings. The max length of the strings should be 50 characters and I'm making a string with that size. I'm getting the strings using argv. How can I detect if the strings are over 50 characters? Can I do it without playing around with memory since I haven't learned this yet. The function for concatenation is stored in a mystrings.h file Here's my current code:

#include <stdio.h>
#include <string.h>
#include "mystrings.h"

int main(int argc, char *argv[]) {
    if (argc == 3) {
        char str1[50];
        char str2[50];

        strcpy(str1, argv[1]);
        strcpy(str2, argv[2]);

        strConcat(str1, str2);

        printf("Concatenated string: %s\n", str1);
    } else {
        printf("Invalid number of arguments passed. Format required:\n <STRING1> <STRING2>\n");
    }
}

CodePudding user response:

As said by Shawn use the strlen() function have a look at the cs50 documentation I find it quite beginner friendly. A possible version of your code could be this:

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) 
{
    if (argc == 3) 
    {
        char str1[50];
        char str2[50];

        if (strlen(argv[1]) > 50 || strlen(argv[2]) > 50)
        {
           printf("Max string length is 50");
           return 1;
        }

        strcpy(str1, argv[1]);
        strcpy(str2, argv[2]);
    
        strConcat(str1, str2);

        printf("Concatenated string: %s\n", str1);
   } 

   else
   {
       printf("Invalid number of arguments passed. Format required:\n <STRING1> "
       "<STRING2>\n");
   }
}

About the concat strings. All it is doing is allocating memory with malloc and then copying the strings to the newly allocated memory while doing some checks to avoid unwanted behavior. It can be a bit confusing in the beginning, but it gets easier.

CodePudding user response:

Take the addition of their strings lengths and ensure it is less than the size of your buffer.

It must be less than the size of the buffer because you must leave room for the null-terminating byte.

No dynamic memory allocation needed.

#include <stdio.h>
#include <string.h>

#define LIMIT 50

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "usage: %s STRING1 STRING2\n", argv[0]);
        return 1;
    }

    if (strlen(argv[1])   strlen(argv[2]) >= LIMIT) {
        fprintf(stderr, "Combined string length is too long.\n");
        return 1;
    }

    char result[LIMIT] = { 0 };
    strcpy(result, argv[1]);
    strcat(result, argv[2]);
    puts(result);
}
  •  Tags:  
  • c
  • Related