Andrea Andrea - 1 month ago 20
C Question

removing printf statment from code breaks program

i have a problem that i can't figure out, so i hope you guys can help me.
I wrote a c program to convert from decimal to binary and write the bits on an integer array, which works fine until i remove a couple of printf statements.Since i thought that this was weird and removing the printf statement doesn't change the logic of the code i tried to recreate the problem on another machine and there it works as one would expect with and without the printfs.
Here is the code:

#include <stdio.h>
#include <stdlib.h>

int main(){

int a;
printf("input a number:\n");
scanf("%d",&a);

int size=sizeof(a);
size=size*8;
printf("size in bits: %d\n",size);


int *p;
p=malloc(size);


int i;
for(i=0;i<size;i++){


p[size-i-1]=a&0x1;

a=a>>1;
}

for(i=0;i<size;i++){

printf("%d",p[i]);
}

printf("\n");

}


when i remove the

printf("input a number:\n");


and

printf("size in bits: %d\n",size);


i get an error

a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.Aborted (core dumped)


If it helps here is the output from uname -a on my machine

Linux aaaa 4.4.0-45-generic #66-Ubuntu SMP Wed Oct 19 14:12:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux


and the output from the other machine

Linux bernard-Inspiron-5558 3.13.0-95-generic #142-Ubuntu SMP Fri Aug 12 17:00:09 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux


my gcc version

gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.2)


and the other one

gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)


does this have something to do with gcc,the OS, or am i doing something wrong in the code?

Answer

Yes, you are not asking for enough memory.

int *p;
p=malloc(size); // size in bytes

int i;
for(i=0;i<size;i++){
    p[size-i-1]=a&0x1;  // size - 1 ints.
    a=a>>1;
}

You need to malloc enough memory for size ints. I.e.

malloc(size * sizeof(int));

Writing past the allocated memory is undefined behavior.