rjmessibarca rjmessibarca - 11 months ago 44
C Question

Malloc 2372 (error) Not able to identify where am I wrong

I am trying to multiply two binary strings ( each of which can have different sizes) without converting them to integer in any step. You may find my code here. It does work many a times , but sometimes it gives me the following error :

a.out: malloc.c:2372: sysmalloc: Assertion `(old_top ==
(((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) -
__builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) ||
((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof
(struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~
((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) &&
((unsigned long) old_end & pagemask) == 0)' failed.

Aborted (core dumped).

I searched for this error on stack overflow but have not been able to figure out the error in my code since the past three days.I know that my code is not the best(using strlen multiple times etc) but still please help me figure out the error in this code (even though the code is long!).

Answer Source
char *chut =malloc((strlen(ans))*sizeof(char));
int j=0;
return chut;

When we allocated chut, we allocated strlen(ans) bytes. So when we do chut[j]='\0'; we need j to be less than strlen(ans). (If we allocated three, then the three valid indexes are 0, 1, and 2. So j must be less than strlen(ans) to be a valid index.)

But the loop condition is j<strlen(ans). So if we exited the loop, it cannot be the case that j<strlen(ans).

So we need j to be less than strlen(ans). But j cannot possibly be less than strlen(ans). Boom.

Add a 1+ before strlen(ans) in the malloc call.

By the way, this code is absurdly hard to understand and debug. It has memory leaks all over the place. And it doesn't keep track of what is const and what is not. Also, there are no comments. This makes it take a lot of experience to debug the code.

At a minimum, add asserts. That would have caught this error for you.