gpt4 book ai didi

将 unsigned int 转换为 int 指针 段错误

转载 作者:行者123 更新时间:2023-11-30 14:59:41 26 4
gpt4 key购买 nike

我试图将无符号整数转换为整数指针,但我不断收到段错误,valgrind 说 free()、delete、delete[]、realloc() 无效。我不明白为什么会收到此错误,因为函数中的所有释放都被注释掉了,并且我防止了 destroy 函数中的段错误。有什么想法吗?

测试代码:

void hugePrint(HugeInteger *p)
{
int i;

if (p == NULL || p->digits == NULL)
{
printf("(null pointer)\n");
return;
}

for (i = p->length - 1; i >= 0; i--)
//printf(" i = %d digit is: %d\n", i, p->digits[i]);
printf("%d", p->digits[i]);
printf("\n");
}

int main(void)
{
HugeInteger *p;

hugePrint(p = parseInt(246810));
hugeDestroyer(p);

return 0;
}

我使用这个结构:

    typedef struct HugeInteger
{
// a dynamically allocated array to hold the digits of a huge integer
int *digits;

// the number of digits in the huge integer (approx. equal to array length)
int length;
} HugeInteger;

我的代码:

#include "Fibonacci.h"
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include<stdio.h>
HugeInteger *parseInt(unsigned int n)
{
HugeInteger *hugePtr = NULL;
int parsedInt;
//If any dynamic memory allocation functions fail within this function, return NULL, but be careful to avoid memory leaks when you do so.
hugePtr = malloc(sizeof(HugeInteger));

if(hugePtr == NULL)
{
// free(hugePtr);
return NULL;
}

// need to allocate for digits too, but how much memory for digits?
// hugePtr->digits = malloc(sizeof(int *));

/* if (hugePtr->digits == NULL)
{
return NULL;
}
*/
// Convert the unsigned integer n to HugeInteger format.
//Need tp do boundary checks?
// is this the right way to do it?
// parsedInt = (int)n;
hugePtr->digits = (int *)n;
hugePtr->length = 7;


return hugePtr;
}
HugeInteger *hugeDestroyer(HugeInteger *p)
{
// printf("in destroy\n");
//If p is not already destroyed, destroy it
if(p != NULL)
{
if(p->digits != NULL)
{
free(p->digits);
free(p);
}
p = NULL;
}
// printf("returning from destroy\n");
return NULL;
}

最佳答案

未定义的行为将被调用,因为:

  • 以实现定义的方式从整数转换的指针被分配给hugePtr->digits,并且可以在hugePrint中取消引用。该指针几乎没有机会成为有效指针。
  • 使用通过malloc()分配且未初始化的p->length值。

通过以下方式避免未定义的行为:

  • 通过 malloc() 系列分配足够的缓冲区并将其分配给 hugePtr->digits
  • 初始化hugePtr->length

关于将 unsigned int 转换为 int 指针 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com