[英]Memory Allocation Error in C
I am trying to get the binary representation of a big integer in GMP. 我正在尝试获取GMP中一个大整数的二进制表示形式。 I am storing 1's and 0's in an array called expBinary .
我将1和0存储在名为expBinary的数组中。 I use malloc to allocate a memory of size of "int", then use realloc to increase this memory whenever a new bit is added.
我使用malloc分配大小为“ int”的内存,然后每添加一个新位就使用realloc增加此内存。 The conversion is running perfectly without any issues, but when I try to allocate any more memory using malloc after the while loop, it is giving me segmentation fault when I call the same code a second time , first time it gives me no segmentation fault.
转换是没有任何问题的完美运行,但是当我尝试后while循环分配使用malloc任何更多的内存,它给我段错误 ,当我调用相同的代码第二次 ,第一次给了我不分段错误。 I have checked and the "expBinary" is not storing anything out of bounds, I have given the code below
我检查了一下,“ expBinary”没有超出范围存储任何东西,我给出了下面的代码
int binarySize = 0;
int * expBinary = malloc(sizeof(int));
int i = 0;
// Run until exp == 0
while(mpz_cmp_ui(exp,0) != 0)
{
binarySize++;
expBinary = (int*) realloc(expBinary,(binarySize));
// Getting LSB of exp
if(mpz_even_p(exp) != 0)
expBinary[i] = 0;
else
expBinary[i] = 1;
// Incrmenting variables
i++;
// Dividing exponent by 2
mpz_tdiv_q_ui(exp,exp,2);
}
// This line is giving error
int * temp = malloc(sizeof(int));
If you are using an int
array, then this is wrong 如果您使用的是
int
数组,那么这是错误的
expBinary = (int*) realloc(expBinary,(binarySize));
it should be 它应该是
expBinary = realloc(expBinary, binarySize * sizeof(*expBinary));
or equivalently, 或等效地,
expBinary = realloc(expBinary, binarySize * sizeof(int));
I prefer sizeof(*expBinary)
for obvious reasons, and also, if realloc()
fails you loose reference to the previous pointer so I recommend this 出于显而易见的原因,我更喜欢使用
sizeof(*expBinary)
,而且,如果realloc()
失败,则您将松散引用以前的指针,因此我建议这样做
void *tmp;
tmp = realloc(expBinary, binarySize * sizeof(int));
if (tmp == NULL)
handleFailureHereAndDontContinueToTheNextLineAndFree_expBinary_Please();
expBinary = tmp;
Now, if you want to print the representation using any printf("%s\\n", expBinary);
现在,如果要使用任何
printf("%s\\n", expBinary);
打印表示形式printf("%s\\n", expBinary);
you should use char *
instead, in that case you should consider that sizeof(char) == 1
always, and you will need one extra byte at the end of the 1
's and 0
's with the value '\\0'
. 您应该改用
char *
,在这种情况下,应始终考虑sizeof(char) == 1
,并且在1
和0
的末尾需要一个额外的字节,其值为'\\0'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.