Copying one part of a string to another in C

769 Views Asked by At

I have problems trying to copy one part of a string into a another. Given these two char pointers:

line points at string cointaining: "helmutDownforce:1234:44:yes"
username points at: NULL

Here's my function that takes these pointers as input:

char* findUsername(char* line, char* username){
    char* ptr = strstr(line, ":");
    ptrdiff_t index = ptr - line;
    strncpy(username, line, index);

    return username;
}

I get segmentation fault during strncpy. How come? The result I want is the function to return a pointer to a string containing helmutDownforce.

2

There are 2 best solutions below

0
On

According to manual of strncpy:

the destination string dest must be large enough to receive the copy

So you must allocate some memory first with malloc for username before calling strncpy.

1
On

This function allocates and returns a new string, so to avoid a memory leak the calling function must be responsible for eventually freeing it. If there is no separator colon in the line it will return NULL.

char* findUsername(char* line){
    char* ptr = strchr(line, ':');
    /* check to make sure colon is there */
    if (ptr == NULL) {
        return NULL;
    }

    int length = ptr - line;
    char *username = malloc(length+1);

    /* make sure allocation succeeded */
    if (username == NULL) return NULL;

    memcpy(username, line, length);
    username[length] = '\0';
    return username;
}