yusuf
yusuf

Reputation: 3781

Logical error with return value from struct in c

I have to return two values from a struct in C:

I have the following data structure:

struct Bar
{
        char *x;
        long y;
};

struct Bar funct();
struct Bar funct()
{
        struct Bar result;
        FILE *fp;
        long lSize;
        char *buffer;

        fp = fopen("list.txt", "rb");
        if (!fp) perror("list.txt"), exit(1);

        fseek(fp, 0L, SEEK_END);
        lSize = ftell(fp);
        rewind(fp);

        buffer = calloc(1, lSize+1);
        if(!buffer) fclose(fp), fputs("memory alloc fails", stderr), exit(1);

        if (1!=fread(buffer, lSize, 1, fp))
                fclose(fp), free(buffer), fputs("entire read fails", stderr), exit(1);

        fclose(fp);
        free(buffer);

        printf("%ld\n", lSize);

        result.x = (char *) buffer;
        result.y = lSize;
}

Instead of structure, when I implement the same code in a char function, I used to get buffer as a char array, and lSize as 744.

My main function is the following:

int main()
{
        char *buffer;
        printf("Reading file...\n");
        //buffer = readFile();
        struct Bar result;
        buffer = result.x;
        printf("%s\n", buffer);
        printf("%ld\n", result.y);
        //collect_character_distribution(buffer);


return 0;
}

But in structure, I don't get array value from *buffer, and I get 0 from lSize. I need to return both *buffer and lSize values. For this reason I have to use struct.

How can I fix the problem?

Thanks,

Upvotes: 2

Views: 92

Answers (1)

ameyCU
ameyCU

Reputation: 16607

There are problems with your code -

 free(buffer);                      // don't free it earlier, you later use it 
 printf("%ld\n", lSize);
 result.x = (char *) buffer;       //casting is not needed

You free buffer and then make result.x to point to it . free it afterwards in calling function .

And this -

 if (1!=fread(buffer, lSize, 1, fp))
            fclose(fp), free(buffer), fputs("entire read fails", stderr), exit(1);

You should probably avoid writing like this . It represent quite unclearly .

You can clearly write like this -

 if(1!=fread(buffer, lSize, 1, fp)){
        fclose(fp);
        free(buffer);
        fputs("entire read fails", stderr);
        exit(1);
 }

make changes in pervious if also accordingly .

Note - You said you want to return something from function but your code doesn't seem to do so .

Upvotes: 5

Related Questions