I'm getting the exact output I want but I keep getting an error that says "Run-Time Check Failure #2 - Stack around the variable 'c' was corrupted." Now I have to for this assignment use strncpy, and strncat and I'm trying to append two strings togethor with the max amount being define with result_maxlength".

I understand I'm overrunning the strncpy, and strncat. And that I need a '\0' to stop the buffer. but I'm still confused on how to exactly fix it. I've had some people say to do result_maxlength-1 but that never solves the issue. Any help would be appreciated.

#include <iostream>
#include <cstring>
using namespace std;

void concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength);
int main()
{
   char a[] = "Woozle";
   char b[] = "Heffalump";
   char c[5];
   char d[10];
   char e[20];
   concat(a, b, c, 5);
   concat(a, b, d, 10);
   concat(a, b, e, 20);
   cout << c << "\n";
   cout << d << "\n";
   cout << e << "\n";
   return 0;
}
void concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength)
{


    strncpy (result,a, result_maxlength);
    result[result_maxlength] = '\0';
    strncat (result,  b, result_maxlength);
    result[result_maxlength] = '\0';
}

How much space has been reserved for char a[] = "Woozle";?? In total?

So will it actually fit into char c[5];?

How much space for char b[] = "Heffalump";

So will it actually fit into char c[5]; too?

Edited 4 Years Ago by WaltP

You aren't checking anything with result_maxlength. There are no tests what-so-ever in your code.

Sit down with pencil and paper and draw out the variables, contents, and their storage space.

Then follow your program line by line and fill in the values.

And don't forget the \0s

There are no tests what-so-ever in your code.

Yes, there are. They are inside the strncpy and strncat functions.

I've had some people say to do result_maxlength-1

They are right. In your first concat call, this -> result[result_maxlength] = '\0';
turns to -> c[5] = '\0';. You're going out of bounds. Same with the following calls.

strncat (result, b, result_maxlength);

strncat doesn't work like this. Check out the link above. What you need here is
this -> strncat (result, b, result_maxlength - 1 - strlen(result));

This article has been dead for over six months. Start a new discussion instead.