I am experimenting with malloc and realloc and came up with code for the following problem:
I want to create a string of unknown size without setting any restrictions. I could ask the user for nr characters, but I rather resize str as the user type of each character.
So, I tried to do this using malloc + realloc, and the idea was that every time the user enters a new char, I use realloc to request a +1 piece of memory to store the char.
While trying to implement this, I made a mistake and ended up doing the following:
int main () { char source[10]; int i, j; for (i=0, j=65; i<10; i++, j++) { source[i] = j; } char *str = malloc(2 * sizeof(char)); int current_size = 1; i = 0; while(i<10) { char temp = source[i]; str[current_size-1] = temp; str[current_size] = '\0'; current_size++; printf("new str = '%s' | len = %d\n", str, strlen(str)); i++; } printf("\nstr final = %s\n", str); return 0; }
Please note that the realloc part is not yet implemented.
I compiled and executed this code and got the following output
new str = 'A' | len = 1 new str = 'AB' | len = 2 new str = 'ABC' | len = 3 new str = 'ABCD' | len = 4 new str = 'ABCDE' | len = 5 new str = 'ABCDEF' | len = 6 new str = 'ABCDEFG' | len = 7 new str = 'ABCDEFGH' | len = 8 new str = 'ABCDEFGHI' | len = 9 new str = 'ABCDEFGHIJ' | len = 10
I found these results strange because I expected the program to crash: str has room for 2 characters, and the code adds more than 2 characters to str without asking for more memory. In my opinion, this means that I write to a memory that I do not own, so it should give a runtime error.
So ... Why does this work?
(The compiler is GCC 4.3.4.)
Thanks in advance.
EDIT: One of the commenters suggesting that calling free () can lead to an error signal. I tried calling free () with the above code, and no error occurred while executing the code. However, after adding more elements to the original array, as well as to call for free, the following error was received:
* glibc ./prog detected: free (): invalid next size (fast): 0x09d67008 **