Dynamically grown array of strings

前端 未结 2 1707
余生分开走
余生分开走 2021-01-13 20:10

I\'m trying to build a dynamically grown array of strings. Neither the number of strings nor the length of each string is known at compile time. Here\'s the code I came up w

相关标签:
2条回答
  • 2021-01-13 20:50

    The following statement makes both result[0] and temp point to the same memory address:

    result[0]=temp;
    

    Having performed the above assignment, you then free(temp) and try to access result[0]:

    free(temp);
    printf ("%s \n", result[0]);
    

    This is undefined behaviour, since you're accessing the memory that's just been deallocated.

    The same goes for the identical code you have for result[1].

    0 讨论(0)
  • 2021-01-13 20:52
    • In the first example you are using a string after freeing it
    • In the second example you are strcating to unallocated memory (plus the uneducated realloc(result[0] makes no sense)

    You could try this:

    char **result = NULL;
    result = realloc(result, sizeof(char *) * 1);
    
    result[0] = strdup("hello");
    
    /* ... */
    
    result = realloc(result, sizeof(char *) * 2);
    result[1] = strdup(" world");
    

    Now strdup isn't standard but it's not hard to steal it / fake it. Here's one attempt:

    char *strdup2(const char *str)
    {
        size_t len;
        char *rval = NULL;
    
        len = strlen(str);        /* We should probably check this. */
        rval = malloc(len + 1);   /* And this. */
    
        memcpy(rval, str, len);
        rval[len] = 0;
    
        return rval;
    }
    

    EDIT

    I was under the (possibly wrong) impression you want to later modify the strings. If that is not the case, simply storing them (without strdup) is adequate:

    result[0] = "hello";
    
    0 讨论(0)
提交回复
热议问题