2017-03-05 201 views
0

我試圖將一個無符號整數轉換爲一個整型指針,並且我不斷收到一個段錯誤,valgrind說無效free(),delete,delete [],realloc ()。我不明白爲什麼我得到這個錯誤,因爲函數中的所有釋放都被註釋掉了,並且我在destroy函數中防止了segfaults。有任何想法嗎?將unsigned int轉換爲int指針seg-fault

測試代碼:

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

請發佈一個[最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve),其中使用了結構的定義,包含頭文件。 – MikeCAT

+0

「這是做到這一點的正確方法嗎?」。編號'hugePtr-> digits =&parsedInt'這個指針指向一個* local *變量。調用者不能使用該指針,因爲當函數退出時局部變量超出範圍。 – kaylum

+0

標題「將unsigned int轉換爲int指針」看起來很混亂。我以爲你正在做一些危險的事情,比如'unsigned int a = 12345; int * p =(int *)a;'而實際上你不是。 - 哦......你*在你的編輯中做了*它太糟糕了...... – MikeCAT

回答

1

未定義行爲將被調用,因爲:

  • 以實現定義的方式從整數轉換的指針被指定給hugePtr->digits,並且它可能在hugePrint中被取消引用。指針幾乎沒有機會成爲有效的指針。
  • 使用通過malloc()分配且未初始化的值p->length

避免發生不可預料的行爲方式:

  • 通過malloc()家庭分配足夠的緩衝,並將其分配給hugePtr->digits
  • 初始化hugePtr->length
相關問題