Safe char array copy (C Programming)


I'm trying to copy a string with a dynamic length into a fixed length string in C.  I need to be careful that I'm only copying the variable string to it's length and that I"m not copying more than the size of the fixed string. Below is what I'd like to do but it seems like a lot of coding. Is there a more elegant way to do this?


#define MAX_FIXED_STRLEN  128
int dynStrLen = 23465;
char * variableStr = NULL;
char[MAX_FIXED_STRLEN] fixedStr = {0};
int maxLen = 0;

variableStr =malloc(dynStrLen+1);
strcpy(variableStr, "my variable string");

if (strlen(variableStr) < MAX_FIXED_STRLEN) {
  maxLen = strlen(variableStr);
else {

strncpy(fixedStr, variableStr, maxLen);

if (variableStr) {

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Just use strncpy directly :
char * variableStr;
char[MAX_FIXED_STRLEN] fixedStr = { 0 };

strncpy(fixedStr, variableStr, MAX_FIXED_STRLEN - 1);
fixedStr[MAX_FIXED_STRLEN - 1] = '\0';

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
php-newbieAuthor Commented:
Hmm, what if the variable string is shorter than the fixed string? Will the strncpy handle this?
>> Hmm, what if the variable string is shorter than the fixed string? Will the strncpy handle this?

Yes. It will only copy up to the end of the string.
php-newbieAuthor Commented:
Thanks a bazillion!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.