Basic use of strcpy_s , strcat_s

147 views Asked by At

Code

char* CreateString(char* string1, char* string2) {
    
    int length = strlen(string1) + strlen(string2);

    // Allocate memory for the resulting string
    char* result = malloc((length) * sizeof(char)); 

    // Concatenate the two strings
    strcpy_s(result, sizeof result, string1);
    strcat_s(result,sizeof result, string2);
    return result;
}

I have this simple code of mine , all i want to do is add them together, but whenever I use strcpy_s or strcat_s it gives this error in the picture But it works if I use the CRT library.

Another question is that did I use the Pointers correctly? I'm new to this topic and it is confusing so I don't really understand it.

I tried to add Two Sentences together

1

There are 1 answers

1
0___________ On
  1. strings require null terminating character at the end. So the buffer is too short.

  2. sizeof result gives the size of the pointer not the size of the referenced object.

char* CreateString(char* string1, char* string2) {
    
    size_t length = strlen(string1) + strlen(string2) + 1;
    // or for Windows
    // rsize_t length = strlen(string1) + strlen(string2) + 1;

    // Allocate memory for the resulting string
    char* result = malloc((length) * sizeof(*result)); 

    // Concatenate the two strings
    strcpy_s(result, length, string1);
    strcat_s(result, length, string2);
    return result;
}