Search code examples
cstringpointerssegmentation-faultstrncpy

Segmentation fault while performing strncpy to pointer to an array of strings C


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


Solution

  • 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
        }
    }