-2

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!).

Community
  • 1
  • 1
humble
  • 2,016
  • 4
  • 27
  • 36

1 Answers1

2
char *chut =malloc((strlen(ans))*sizeof(char));
int j=0;
for(j=0;j<strlen(ans);j++)
    chut[j]=ans[j+1];
chut[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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • sorry ...This is literally my first year in coding... I will in future try to make it more "readable"...Thanks a lot ....Can't thank you enough...Also can you please tell what "assert" is? – humble Sep 03 '16 at 09:23
  • Can you suggest me the how may I avoid memory leaks...I know that I should free the pointers to do so but the problem is I can't because the same string is being called in multiple functions – humble Sep 03 '16 at 09:30
  • 1
    @rjmessibarca An `assert` is a line of code that detects a condition that the programmer expects will never happen and reports it. In this case, the programmer expected `j` to be `<=strlen(ans)`, and so should have assert that. – David Schwartz Sep 03 '16 at 19:03