I have been working on and off on an assignment for my C class for the last few days and encountered a curious crash concerning the realloc() function in C. Even the C/C++ programmers in house could not answer me right away what might be wrong with my code.
First i create the memory block in one function:
char *line = (char *)malloc( sizeof(char) * BUFSIZE);
Then i call getMoreBuf(start_of_block, end_of_block)
int getMoreBuf(char *start, char *end)
{
char *newBuf = 0;
int newSize = (end - start) + BUFSIZE;
newBuf = (char *)realloc(start, sizeof(char) * newSize);
if(NULL == newBuf) {
printf("No virtual RAM available");
}else{
start = newBuf;
}
return newSize;
}
Depending on what i set the BUFSIZE to, it crashes after the 5th call (BUFSIZE = 1) or the 3rd call (BUFSIZE = 5) and replaces the read in characters with nonsense.
Could someone point me towards my error(s) and give suggestions where to read up on to fix them?
Any help is appreciated. 🙂
Bonus Question: I malloc a memory block with pointer 1 pointing to the start and later pointer 2 point2 towards a single block in the memory block. I realloc() the block and the block is moved due to size issues, does the pointer 2 still point to the old (now useless) block or does it “move” with the realloc to the new position of the memory block?
(Also for the future, should i put that extra question into a new question or can i leave it in here since it is strongly related to the first question?)
Thank you all for your input, it helped me a great deal to figure out what went wrong.
If i could i would mark each as the right answer since each helped my in some form to understand a bit more about all this damn pointer business. =)
I think your problem is that you’re only changing the local variable
start… You need to use a pointer.And then you’d call it like: