For reasons that I promise exist, I’m reading input character by character, and if a character meets certain criteria, I’m writing it into a dynamically allocated buffer. This function adds the specified character to the “end” of the specified string. When reading out of the buffer, I read the first ‘size’ characters.
void append(char c, char *str, int size)
{
if(size + 1 > strlen(str))
str = (char*)realloc(str,sizeof(char)*(size + 1));
str[size] = c;
}
This function, through various iterations of development has produced such errors as “corrupted double-linked list”, “double free or corruption”. Below is a sample of how append is supposed to be used:
// buffer is a string
// bufSize is the number of non-garbage characters at the beginning of buffer
char *buft = buffer;
int bufLoc=0;
while((buft-buffer)/sizeof(char) < bufSize)
append(*(buft==),destination,bufLoc++);
It generally works for some seemingly arbitrary number of characters, and then aborts with error. If it’s not clear what the second code snippet is doing, it’s just copying from the buffer into some destination string. I know there’s library methods for this, but I need a bit finer control of what exactly gets copied sometimes.
Thanks in advance for any insight. I’m stumped.
This function does not append a character to a buffer.
First, what is
strlen(str)? You can say “it’s the length ofstr“, but that’s omitting some very important details. How does it compute the length? Easy —strmust be NUL-terminated, andstrlenfinds the offset of the firstNULbyte in it. If your buffer doesn’t have a NUL byte at the end, then you can’t usestrlento find its length.Typically, you will want to keep track of the buffer’s length. In order to reduce the number of reallocations, keep track of the buffer size and the amount of data in it separately.
Another problem
This code:
It only changes the value of
strinappend— it doesn’t change the value ofstrin the calling function. Function arguments are local to the function, and changing them doesn’t affect anything outside of the function.Minor quibbles
This is a bit strange:
The
(char *)cast is not only unnecessary, but it can actually mask an error — if you forget to include<stdlib.h>, the cast will allow the code to compile anyway. Bummer.And
sizeof(char)is 1, by definition. So don’t bother.