我将内存分配给指向它可能具有的最大字符大小的指针。 然后,我不得不编写代码,它将根据从文件中读取的值更改其值,并且我需要知道指针中的值的长度是多少,所以我使用了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的方式,但我反正写它,所以我记得应该在那里放置什么样的价值。
方便查看'itoba'的代码 –
我添加了代码itoba – Dani
'return temp;'返回一个指向局部变量的指针,当函数退出时它会消失。 –