1

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
    }`
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
noor napso
  • 113
  • 5
  • 2
    The `get_song_name` opens the same file over and over again, every time reading one single line from the beginning and returning it. And what's worse, it returns a pointer to the local `str` array, a variable whose life-time will end when the function returns making the returned pointer invalid. – Some programmer dude Dec 03 '21 at 14:07

2 Answers2

2

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;
}
tstanisl
  • 13,520
  • 2
  • 25
  • 40
1

This function

char* get_song_name(const char* song)

can invoke undefined behavior because it returns an invalid pointer that points to a local array of the function that will not be alive after exiting the function

char str[9999];
//...
char* s = str;
return s;

Moreover the function always returns the same pointer (the address of the first element of the local array). So this loop

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

does not make a sense.

You need to allocate dynamically a character array within the function get_song_name a pointer to which will be returned from the function.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335