• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 481
  • Last Modified:

Safe char array copy (C Programming)

Hi,

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?

Thanks!

#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 {
  maxLen = MAX_FIXED_STRLEN;
}

strncpy(fixedStr, variableStr, maxLen);


if (variableStr) {
  free(variableStr);
  variableStr=NULL;
}


0
php-newbie
Asked:
php-newbie
  • 3
  • 2
1 Solution
 
Infinity08Commented:
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

0
 
php-newbieAuthor Commented:
Hmm, what if the variable string is shorter than the fixed string? Will the strncpy handle this?
0
 
Infinity08Commented:
>> 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.
0
 
php-newbieAuthor Commented:
Thanks a bazillion!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now