1

I am writing a code in which the function "verif" is supposed to verify whether the characters differ in a string or not. This function is then called for each line in a file. However, although i verified and the function is ok, there is something i am doing wrong concerning the returning of pointers or the attribution in the main function. The result i get is 'null null null' for each line of the file ( my file has 3 lines) This is my code:

#include <stdio.h>
#include <stdlib.h>


char* verif (char line[])
{
    int i,j,ok=1;
    char v[5];
    for (i=0; i<strlen(line); i++)
    {
        for (j=i+1; j<strlen(line); j++)
        {
            if (line[i]==line[j])
            {
                ok=0;
                break;
            }
        }
    }
if (ok==0) strcpy(v,"No");
else strcpy(v,"Yes");

return v;

}


int main()
{
    FILE *f;
    char sir[30];
    char* ctrl;
    if ((f=fopen("fis.txt","r"))==NULL) exit(1);


    while (fscanf(f,"%[^\n]",sir))

    {
        if (fgetc(f)==EOF) break;
        puts(sir);
        ctrl=verif(sir);
        printf("%s",*ctrl);}





    }
Mary Poppins
  • 79
  • 13
  • 1
    You are returning the address of a local variable, which is no longer valid when returning from the function. – Osiris Jan 21 '19 at 20:12
  • 1
    Possible duplicate of [Returning an array using C](https://stackoverflow.com/questions/11656532/returning-an-array-using-c) – Osiris Jan 21 '19 at 20:12
  • try ```return ok==0 ? "No" : "Yes";``` – Hawk Jan 21 '19 at 20:15
  • @osiris what should i modify in my function in order to work without doing what Hawk suggested? – Mary Poppins Jan 21 '19 at 20:26
  • @MaryPoppins The link for the duplicate contains a few approaches. You could allocate the space with `malloc` or make the array `static`. – Osiris Jan 21 '19 at 20:45

1 Answers1

0

You are returning the address of a local variable from a function with your statement return v;

Your options:

  • Declare v as static, so that it goes into the process' data section, rather than on the local stack for the function.
  • Use the heap (malloc/free) to manage the string in v, since objects on the heap persist beyond the lifetime of the scope they are declared in if they are not freed.
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85