1

I have an char array and I am trying to copy a part of it (tokenization) into 0th index of array of pointer to char using the strncpy function. But during runtime a segmentation fault occurs.

Code example:

char array[30] = "ls -l";
char* args[10];

strncpy(args[0], array + 0, 2);
1
  • You try copy only the first 2 characters without even putting a NUL terminator. Is this intentional? Commented May 7, 2021 at 10:15

2 Answers 2

1

char *args[10] has the following declaration:

declare args as array 10 of pointer to char

That is to say, we have an array of uninitialized pointers. We'll need to make those pointers point somewhere first, before trying to place characters there. Remembering that we must NUL terminate ('\0') C strings, we can simultaneously allocate and NUL out space for our string by using calloc.

This will make space for just 'l', 's', and our mandatory '\0'.

char original_command[30] = "ls -l";
char *args[10] = { 0 };
args[0] = calloc(3, sizeof (char));
strncpy(args[0], original_command, 2);

Alternatively, we can use malloc, but we must remember the NUL terminating byte.

args[0] = malloc(3);
strncpy(args[0], original_command, 2);
args[0][2] = '\0';

It's generally a good idea to always initialize our variables - see how we initialize our args array to be full of NULL pointers (0). Makes it very clear they don't point anywhere useful yet.

Also note that strncpy does not place a NUL terminating byte if it was not found in the first n bytes of our source string. This is why it's very important to manually terminate our destination string.

Additionally, any call to an *alloc function must be matched later by a call to free, when we are finished using that memory.

/* Do whatever needs to be done */
/* ... */
free(args[0]);
Sign up to request clarification or add additional context in comments.

2 Comments

sizeof(char) is by definition 1
@0___________ Sure is. This, however, showcases exactly what the second argument to calloc is.
0

You need to allocate space for the copied string content; char* args[10] reserves only space for holding the pointer to the content, not for the content itself. And don't forget to reserve space for the string terminating character '\0' then.

args[0] = malloc(2+1);
strncpy(agrs[0],array+0,2+1);
agrs[0][2] = '\0';

4 Comments

It would also be a good idea to null terminate the string in args[0].
strncpy(agrs[0],array+0,2+1) looks fishy anyway.
This has UB as strncpy will copy the first 3 bytes (being 'l', 's', ' '), and not NUL terminate properly.
Seems, people have problems writing args. Second time in this thread. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.