I've decided to learn C and C++ but Im struggling with a simple task and cant get my head around it. I would really appreciate the help.
In one of my functions i make a pointer * linesLenght and I call another function to allocate memory and fill array. In one of the functions there's a reallocation that happens 1-3 times. On the first time everything goes right. But when reallocating on the 2nd try, i get a corrupted size vs. prev_size error.
Code:
1st. function
char * wordWrap (int width, const char * src ){
ulong len = strlen(src);
ulong lines = getLines(width,len);
int * linesLenght = getLinesLen(&lines, src, len, width);
... }
2nd function
int * getLinesLen(ulong * lines, const char * src, ulong srcLen, int maxLine){
int * linesLen = malloc((*lines) * sizeof(int));
ulong counter = 0;
for(int i = 0; i < srcLen; i++)
{
///other hidden logic....
if(counter == *lines)
{
printf("out! Must resize\n");
resizeLinesArr(counter + 1, &linesLen);
*lines += 1;
}
}
*lines = counter;
return linesLen;
}
3rd functin (HERE I GET THE ERROR)
void resizeLinesArr(ulong arrLen, int ** arr)
{
int * tmp = realloc(*arr, arrLen * sizeof(int));
if(tmp == NULL)
{
printf("realloc problem\n");
free(*arr);
exit(1);
}
else
{
*arr = tmp;
}
}
This error:
corrupted size vs. prev_size
is an error that malloc (or realloc) prints when its internal record-keeping variables have been corrupted. The problem is almost certainly not in the line that calls realloc. At some point, you either:
free() it.This sort of thing is usually pretty hard to track down. I suggest that you try running the program using valgrind. First, add -g to the list of options you pass to the compiler. This turns on debugging information, which lets Valgrind give you line numbers instead of just function names.
Then run your program like this:
valgrind ./your_program
Valgrind will look at every memory access and check if it violates the two rules I described above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With