Hello,
my program: (compiled with : gcc -lm prog1.c)
Code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
// Returns the exponent of the largest power of 2 less than x.
int pow2(int x)
{
int i;
for(i=0; pow(2, i)<=x; i++)
;
return i-1;
}
int main()
{
int a, n, k, i;
printf("give a positif integer \n");
scanf("%d", &a);
k = n = pow2(a);
printf("n = %d\n", k);
int *tab = (int *)malloc((n+1)*sizeof(int));
for(i=0; i<=n; i++)
tab[i]=0;
for(i=0; i<=n; i++)
{
tab[n-k]=1;
a=a-pow(2, k);
k=pow2(a);
}
for(i=0; i<=n; i++)
printf("%d ", tab[i]);
printf("\n");
free(tab);
return 0;
}
all work fine until 31 but for 32 I get:
32
n = 5
1 0 0 0 0 0
*** Error in `./a.out': free(): invalid next size (fast): 0x0000560569d5d830 **
if in the line : int *tab = (int *)malloc((n+1)*sizeof(int));
I replace n+1 with n+2 the problem disappears:
255
n = 7
1 1 1 1 1 1 1 1
I do not understand why n + 1 does not work beyond 31 ?
Thanks in advance for your help