0

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.

cass
  • 11
  • 1
    Are you passing a `NULL`-pointer to `strncpy()`? – EOF Sep 03 '16 at 15:06
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Sep 03 '16 at 15:15
  • Post calling code to `findUsername()`. – chux - Reinstate Monica Sep 04 '16 at 00:28

2 Answers2

2

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;
}
NovaDenizen
  • 5,089
  • 14
  • 28
1

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.

redneb
  • 21,794
  • 6
  • 42
  • 54