1

I am trying to copy substring of s to pointer to an array of strings. And below is my code. I have allocated the memory using malloc. But when I try to perform strncpy, I get segmentation fault. Can anyone please let me know if there is anything wrong with my code? Or is it allowed to strncpy on a array of pointers to strings

s is a string of length 32

char **suptr = (char **)malloc(sizeof(char *) * 11);  
if(suptr != NULL)
{
strncpy(suptr[0], s, 10);
strncpy(suptr[1], s+10, 10);
strncpy(suptr[2], s+20, 10);
strncpy(suptr[3], s+30, 2);
}

Thanks in advance

5
  • 1
    It's bad practice (an unnecessary) to cast the result of malloc. Commented Dec 13, 2020 at 2:59
  • What is the size of s? Commented Dec 13, 2020 at 2:59
  • Its 32 bit string Commented Dec 13, 2020 at 2:59
  • I mean the length of the string s Commented Dec 13, 2020 at 3:00
  • The length is 32 Commented Dec 13, 2020 at 3:02

1 Answer 1

1

You've allocated an array of char pointers. However, those pointers are uninitialized. That is, they contain junk data and don't actually point anywhere meaningful. So, when you try to copy data to them, you're writing to invalid addresses.

Each pointer needs to be directed to a valid section of memory first. One easy way to accomplish this is:

for (int k=0; k<11; k++) {
    suptr[k] = malloc(sizeof(char)*10); // Or whatever length you want.
    if ( !suptr[k] ) {
        // handle the error
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.