Home > Software design >  Assigning string with null terminators inside it in one line in C
Assigning string with null terminators inside it in one line in C

Time:08-27

I am trying to figure out if there is a way to assign a string which includes null terminators within the string as well as the end in one go. I am able to assign it manually, char by char, but is there a way to do this in one go? I looked for a similar question but couldn't find one.

Where I'm stuck. EX:

char *argvppp = (char *)malloc(14);
argvppp = "mine\0-c\0/10\0/2.0\0"; // forward slash before the 10 after the null terminator

When I try to read from argvppp, like this:

printf("%s\n", argvppp);
printf("%s\n", argvppp 5);
printf("%s\n", argvppp 8);
printf("%s", argvppp 11);

This is what I get:

mine
-c
/10
[blank]

And when I try to just not escape it like this:

argvppp = "mine\0-c\010\0/2.0\0"; // no forward slash before the 10

This is what I get:

mine
-c
[blank]
.0

Is there a reliable way to do this without having to manually assign assign char by char?

What does work:

argvppp[0] = 'm';
argvppp[1] = 'i';
argvppp[2] = 'n';
argvppp[3] = 'e';
argvppp[4] = '\0';
argvppp[5] = '-';
argvppp[6] = 'c';
argvppp[7] = '\0';
argvppp[8] = '1';
argvppp[9] = '0';
argvppp[10] = '\0';
argvppp[11] = '2';
argvppp[12] = '.';
argvppp[13] = '0';
argvppp[14] = '\0';

I'm just wondering if there would be a way around this manual method.

CodePudding user response:

Use memcpy()

char *argvppp = malloc(sizeof "mine\0-c\0/10\0/2.0\0");
memcpy(argvppp, "mine\0-c\0/10\0/2.0\0", sizeof "mine\0-c\0/10\0/2.0\0");

When you don't put a / between \0 and 10, you get a single character \010. You can solve this by splitting the string literal apart.

"mine\0-c\0" "10\0/2.0\0"

Adjacent string literals are automatically concatenated.

CodePudding user response:

= does not copy the string only assigns the pointer to string literal to your variable. The memory allocated is lost. string literals cannot be modified as it invokes UB (undefined behaviour)

You need to copy the string literal into the memory referenced by te pointer:

define STR "mine\0-c\0/10\0/2.0\0";

char *argvppp = malloc(sizeof(STR));
memcpy(argvppp, STR, sizeof(STR));

you can also:

char argvppp[] = "mine\0-c\0/10\0/2.0\0";

CodePudding user response:

You could try something like this where your data is clearly visible.

int main() {
    char *segs[] = { "mine", "-c", "10", "2.0" };
    char buf[ 50 ]; // long enough?!
    char *at = buf;

    for( int i = 0; i < sizeof segs/sizeof segs[0]; i   )
        at  = sprintf( at, "%s", seg[i] )   1; // NB  1 is beyond '\0'

    /* Then examine the contents of 'buf[]' character by character. */        
    return 0;
}
  •  Tags:  
  • c
  • Related