【问题标题】:strlen and free memory [closed]strlen 和空闲内存
【发布时间】: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 指向的内存已经被释放了。

标签: c malloc free strlen


【解决方案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;
}

顺便说一句:您应该删除char *StudIDcpy = (char*)malloc(sizeof(char) * 15);,因为malloc() 返回的指针值稍后会被itoba(IDtemp); 丢弃。结果这个malloc()分配给StudIDcpy的内存永远不会被释放,导致内存泄漏。

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2012-09-18
    • 2016-12-24
    相关资源
    最近更新 更多