2016-03-30 44 views
-5

我将内存分配给指向它可能具有的最大字符大小的指针。 然后,我不得不编写代码,它将根据从文件中读取的值更改其值,并且我需要知道指针中的值的长度是多少,所以我使用了strlen()函数。strlen和空闲内存

我得到了我需要的东西。 当我试图释放该指针的内存时发生问题。该程序崩溃了,我假设我正在做一些“回肠”,并想知道为什么以及如何解决它。

这里是代码的一部分:

char *StudID = (char*)malloc(sizeof(char)*15); 
char *StudIDcpy = (char*)malloc(sizeof(char) * 15); 
fread(stud[i].ID, sizeof(char), 4, in); 
stud[i].ID[4] = '\0'; 
IDtemp = atoi(stud[i].ID);//convert ID string to integer and store value in IDtemp 
StudIDcpy = itoba(IDtemp);//convert integer to binary number as a string 
strcpy(StudID, StudIDcpy); 
IDtemp = strlen(StudIDcpy); 
free(StudIDcpy); // <---- I BELIEVE THIS IS WHERE IT CRASHES 

这里是我的itoba()功能:

char *itoba(int a){ 
    int i = 0, j; 
    char temp[15]; 
    while(a){ 
     if (a % 2)temp[i] = '1'; 
     else temp[i] = '0'; 
     i++; 
     a = a/2; 
    } 
    temp[i] = '\0'; 
    for (j = 0; j < i/2; j++)swapc(&temp[j], &temp[i - j-1]); 
    return temp; 
} 

当我知道我没有写sizeof(char),因为它等于1的方式,但我反正写它,所以我记得应该在那里放置什么样的价值。

+0

方便查看'itoba'的代码 –

+0

我添加了代码itoba – Dani

+2

'return temp;'返回一个指向局部变量的指针,当函数退出时它会消失。 –

回答

1

在您的itoba()函数temp中,将返回一个本地数组,它将衰减为指向局部变量的指针。

函数返回后,其局部变量立即“释放”,允许其他人重新使用这些内存空间。因此,它们所持有的值很快将被堆栈中的其他值所覆盖。

可以重写itoba()这样的:

char *itoba(int a) 
{ 
    int i = 0, j; 
    char *temp = malloc(15); // <--- This line is different 
    while(a){ 
     if (a % 2) 
      temp[i] = '1'; 
     else 
      temp[i] = '0'; 
     i++; 
     a = a/2; 
    } 
    temp[i] = '\0'; 
    for (j = 0; j < i/2; j++) 
     swapc(&temp[j], &temp[i - j -1]); 
    return temp; 
} 

BTW:你应该删除char *StudIDcpy = (char*)malloc(sizeof(char) * 15);,因为malloc()返回指针值后来被itoba(IDtemp);丢弃。因此,此malloc()分配给StudIDcpy的内存将永远不会被释放,从而导致内存泄漏。