-4

I am unable to read the data from the file created. This is a very simple code and I simply cannot understand why it is not working. I have just shifted to mac and installed the developer command line tools.

My code is :

int main()
{
    FILE *fp;
    int lines = 0;
    char *data;
    data = (char *)malloc(1000);
    data = NULL;

    fp = fopen("1.txt", "r");
    while (fgets(data, 1000, fp) != NULL)
    {
        printf("%s\n", data);
        lines++;
    }
    printf("Lines = %d\n", lines);
    free(data);
    fclose(fp);
    return 0;
}
Anand Goyal
  • 51
  • 1
  • 1

1 Answers1

1

You allocate space for data and then promptly leak it.

char *data;
data = (char *)malloc(1000);
data = NULL;

You then use fgets() with a NULL pointer, which causes undefined behavior.

fgets(data, 1000, fp)

Perhaps you should remove this line of code?

data = NULL;
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173