Search code examples
cpointersscopereturn-valueundefined-behavior

Function's pointer return keeps changing previous values in an array


im trying to fill a 2d array with strings, problem is that i manage to fill the first index, however when i proceed to the next string it keeps changing the previous indexes. probably an issue with the pointer, this is the relevant code.

char* get_song_name(const char* song)
{
    strip(song);
    FILE* fp = fopen(song, "r");
    char str[9999];
    while(!feof(fp))
    {
        fgets(str,9999,fp);
        puts(str);
        strip(str);
        char* s = str;
        return s;
    }

` DIFFERENT FUNCTION:
for(i=0;i<lines;i++)
    {
        char *st = fgets(buff, 250, fp);
        st = create_path("c:\\Users\\Marian\\Desktop\\beatles", st);
        name[i] = get_song_name(st); //WORKS HOWEVER CHANGES PRVIOUS INDEXES VALUE TOO
    }`

Solution

  • You need to dynamically allocate the string so its lifetime does not end then the functions exits.

    Just replace

    return s;
    

    with

    return strdup(s);
    

    EDIT

    As OP is not allowed to use string.h here one can find an implementation of strdup() found in https://stackoverflow.com/a/37132824/4989451

    #include <stdlib.h>
    
    char *ft_strdup(char *src)
    {
        char *str;
        char *p;
        int len = 0;
    
        while (src[len])
            len++;
        str = malloc(len + 1);
        p = str;
        while (*src)
            *p++ = *src++;
        *p = '\0';
        return str;
    }