Q:

Reading and storing dynamically to char array

I have a file that i want to read from and store the data to a char array that i dynamically allocate memory to after each character read. I want to dynamically allocate memory exactly to that of the size needed. Here is what i have:
FILE *fp;
char *data;
int c=0;

fp=fopen("home/bob/Downloads/filename", "r");
data=malloc(sizeof(char));

do{
    data[c]=fgetc(fp);
    printf("data : %c\n", data[c]);
    c++;
    data=realloc(data, sizeof(char)+c);
} while(data[c]!=EOF);

I get a segmentation fault.

A:

The problem is most likely here:
while(data[c]!=EOF)

Remember that you increase c inside the loop, so data[c] is an uninitialized part of the memory you allocate. This means that you will continue to read character by character as long as this uninitialized data is not (char) -1, which will probably be well beyond the actual end of the file.
Instead try something like this:
char *data = NULL;
size_t c = 0;

for (;;)
{
    const int ch = fgets(fp);
    if (ch == EOF)
        break;  /* Error or end of file */

    char *tmp = realloc(data, c + 1);
    if (tmp == NULL)
        break;  /* Could not allocate memory */

    data = tmp;
    data[c++] = ch;
}

