【发布时间】:2016-03-30 20:50:10
【问题描述】:
我将内存分配给一个指向它可以拥有的最大字符大小的指针。
然后我必须编写代码,根据从文件中读取的值更改其值,并且我需要知道指针中值的长度是多少,所以我使用了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,但我还是写了它,所以我记得应该放什么值。
【问题讨论】:
-
方便查看
itoba的代码 -
我添加了代码 itoba
-
return temp;返回一个指向局部变量的指针,该指针在函数退出时消失。 -
你编译时是否启用了警告?
-
@tikanti-man
char temp[15];分配内存,函数返回时自动释放内存。你不能写strcpy(StudID, StudIDcpy);因为StudIDcpy指向的内存已经被释放了。