将unsigned int转换为int指针seg-fault

时间:2017-03-05 03:02:11

标签: c pointers int unsigned

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

测试代码:

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;
    }

1 个答案:

答案 0 :(得分:1)

将调用

未定义的行为,因为:

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

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

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