Using realloc (X, 0) instead of free() and using malloc with length of a string +1

keont picture keont · May 26, 2013 · Viewed 11.8k times · Source

So I don't really know how to put the title this time. First of all I'd like to say that I've seen several comments on this page about warning if the question is related to "homework". Mine is, but it's also completed and I just want to further understand what is going on with the code.

I have also read posts and books for some time, but I think I am still missing things.

I have 2 lines of code I don't quite understand in the code I worked with. The work is about getting whatever file is used as argument (if it's 0 files, it read from stdin), and print it on the standard output backwards. All of this, talking about C as I tried to put in the tag.

First problem is this:

array = realloc (array, 0);

Where array is defined as

char **array;

And the problem is that free doesn't work, it does not free the space used (maybe I used it wrong? In other place I have known how to use it, but not this time). With the testing I have done and what I have read, I believe that realloc is doing the same, but I'm no 100%.

Second one is:

char* alloc = malloc (strlen ((char*)string)+1);

Where alloc is used to copy the exact length of the line I am going to put into an array, so I can, after that, just print the text backwards.

And the question is why I have to use that +1. I mean if I don't use for some reason it doesn't work, I tried with different numbers and it works everytime, but if I don't do that +1 it does not work correctly.

I know probably the question is too vague and bad written to really be answered but again, I'm not sure about that and I did my best to explain myself (english no mother tongue as it's probably obvious).

Answer

Andrei picture Andrei · May 26, 2013

The behavior of realloc when the size is 0 is different in C11 (the current version). The standard says (7.20.3.1 for C11, 7.22.3.1 for C1x)

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object

So, use free and don't rely on realloc.

When dealing with strings via char* always remember to include one extra character for the null terminator \0. This is the usual way to show where the string ends (the other being an explicit string length).

When using malloc and free remember that they must be matched exactly. You need to free the exact pointer (value) returned by malloc or realloc.