Question: I'm trying to read a string

```
char *string=malloc(sizeof(char));
char *start_string=string; //pointer to string start
while ((readch=read(file, buffer, 4000))!=0){ // read
    filelen=filelen+readch; //string length
    for (d=0;d<readch;d++)
        *start_string++=buffer[d]; //append buffer to str
    realloc(string, filelen); //realloc with new length

```

sometimes this crashes with the following error:

```
   malloc: *** error for object 0x1001000e0: pointer being realloc'd was not allocated

```

but sometimes not, I have no idea how to fix it.

Answer: 
[`realloc()`](http://en.cppreference.com/w/c/memory/realloc) does not update the pointer passed in to it. If `realloc()` is successful the pointer passed in is `free()`d and the address of the allocated memory is returned. In the posted code `realloc()` will attempt to `free(string)` multiple times, which is undefined behaviour.

Store the result of `realloc()`:

```
char* t = realloc(string, filelen);
if (t)
{
    string = t;
}

```
The address of string may change when you call `realloc()`. 

```
char *string=malloc(sizeof(char));
char *start_string=string; //pointer to string start
while ((readch=read(file, buffer, 4000))!=0){ // read
    filelen=filelen+readch; //string length
    for (d=0;d<readch;d++)
        *start_string++=buffer[d]; //append buffer to str
    char* tempPtr = realloc(string, filelen); //realloc with new length

    if( tempPtr ) string = tempPtr;
    else printf( "out of memory" );
}

```