c - removing printf statment from code breaks program -
i have problem can't figure out, hope guys can me. wrote c program convert decimal binary , write bits on integer array, works fine until remove couple of printf statements.since thought weird , removing printf statement doesn't change logic of code tried recreate problem on machine , there works 1 expect , without printfs. here code:
#include <stdio.h> #include <stdlib.h> int main(){ int a; printf("input 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 remove
printf("input number:\n");
and
printf("size in bits: %d\n",size);
i 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 helps here output uname -a on 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 output 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 other 1
gcc version 4.8.4 (ubuntu 4.8.4-2ubuntu1~14.04.3)
does have gcc,the os, or doing wrong in code?
yes, not asking 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 malloc enough memory size ints. i.e.
malloc(size * sizeof(int));
writing past allocated memory undefined behavior.
Comments
Post a Comment