Home > OS >  how to copy LPCSTR string to pointer to char array in C
how to copy LPCSTR string to pointer to char array in C

Time:10-27

I am trying to copy LPCSTR value to pointer to char array. With this code I am getting runtime error and unable to diagnose the root cause here

My code shown below

    LPCSTR src = "R2C7YQT8"; 
    char *dest [4];
    memset(dest, 0, sizeof(dest));
    strncpy_s(dest[0], sizeof(dest[0]), src, 12); 

how to copy LPCSTR string to pointer to char array in C?

CodePudding user response:

strncpy_s(dest[0], sizeof(dest[0]), src, 12); is telling strncpy_s to copy into whatever dest[0] points to. dest[0] is a NULL pointer (dest itself is an array of four such pointers), so you invoke undefined behavior by trying to write to where the NULL pointer points.

Either:

  1. You need to make dest a char array of any appropriate size and copy to dest itself, or
  2. You need to initialize the pointer in dest[0] to something useful (and sufficiently large) then copy into it.

In both cases, passing sizeof(dest[0]) is wrong; you're telling it to copy a number of bytes equal to the size of one pointer, not the data it points to.

Case #1's solution:

LPCSTR src = "R2C7YQT8"; 
char dest[9]; // Allocate enough space for the whole string as plain char array; can use higher number if desired
memset(dest, 0, sizeof(dest));
strncpy_s(dest, sizeof(dest), src, 12); // copy to dest directly, sizeof(dest) okay because it's local array

Case #2's solution:

LPCSTR src = "R2C7YQT8"; 
char *dest[4];
memset(dest, 0, sizeof(dest));
size_t srclen = strlen(src); // Compute length of input string
dest[0] = malloc(srclen   1);  // Allocate space   1 byte for NUL terminator
strncpy_s(dest[0], srclen   1, src, 12);  // Copy it up to that many characters

Note that case #1 can be simplified when it's a literal string to just:

char dest[] = "R2C7YQT8";

which will automatically size dest and initialize it directly with no intermediate steps (it might in fact perform a memcpy-like operation from global data for larger strings, or it might just insert direct stack manipulation that renders the bytes correct), but that's restricted to the literal string and direct initialization case (you couldn't do this with a LPCSTR passed to a function or the like).

  • Related