如何在struct中释放指针?

时间:2022-09-06 18:42:49

This is my code:

这是我的代码:

typedef struct bobTheBuilder{
    char *name;
    int fix;
    int max;
};

int main(void){

    struct bobTheBuilder bob;
    initBob(&bob);
    del(&bob);

    system("PAUSE");
    return (0);
}

void initBob(struct bobTheBuilder *currBob)
{
    char *n="bob";
    currBob->name = (char*)malloc(sizeof(char)*strlen(n));
    strcpy((*currBob).name, n);
    (*currBob).fix = 0;
    (*currBob).max = 3;
}

void del(struct bobTheBuilder *currBob)
{
    free(currBob->name);
}

Visual studio breaks at the free sentence.

Visual Studio打破了免费句子。

What should i do? Is the problem with the free or the malloc?

我该怎么办?是免费还是malloc的问题?

1 个解决方案

#1


The line

currBob->name = (char*)malloc(sizeof(char)*strlen(n));

is wrong because

是错的,因为

  1. You did not include the space for the NUL-terminator.
  2. 您没有包含NUL终结符的空间。

  3. You should not cast the result of malloc(and family) in C.
  4. 你不应该在C中强制转换malloc(和family)的结果。

Fix the problems by using

通过使用来解决问题

currBob->name = malloc(strlen(n) + 1);

If you are wondering why I've removed sizeof(char), it is because sizeof(char) is guarenteed to be 1. So, it is not necessary.

如果你想知道为什么我删除了sizeof(char),那是因为sizeof(char)被保证为1.所以,没有必要。


As @EdHeal mentions in a comment, there is a function called strdup() that does malloc+ strcpy. It is POSIX function. If it is available, you can shorten

currBob->name = malloc(strlen(n) + 1);
strcpy((*currBob).name, n);

to

currBob->name = strdup(n);

by using this function. Also, note that

通过使用此功能。另外,请注意

(*currBob).fix = 0;
(*currBob).max = 3;

is equivalent to

相当于

currBob -> fix = 0;
currBob -> max = 3;

as @Edheal mentions in another comment.

正如@Edheal在另一条评论中提到的那样。

#1


The line

currBob->name = (char*)malloc(sizeof(char)*strlen(n));

is wrong because

是错的,因为

  1. You did not include the space for the NUL-terminator.
  2. 您没有包含NUL终结符的空间。

  3. You should not cast the result of malloc(and family) in C.
  4. 你不应该在C中强制转换malloc(和family)的结果。

Fix the problems by using

通过使用来解决问题

currBob->name = malloc(strlen(n) + 1);

If you are wondering why I've removed sizeof(char), it is because sizeof(char) is guarenteed to be 1. So, it is not necessary.

如果你想知道为什么我删除了sizeof(char),那是因为sizeof(char)被保证为1.所以,没有必要。


As @EdHeal mentions in a comment, there is a function called strdup() that does malloc+ strcpy. It is POSIX function. If it is available, you can shorten

currBob->name = malloc(strlen(n) + 1);
strcpy((*currBob).name, n);

to

currBob->name = strdup(n);

by using this function. Also, note that

通过使用此功能。另外,请注意

(*currBob).fix = 0;
(*currBob).max = 3;

is equivalent to

相当于

currBob -> fix = 0;
currBob -> max = 3;

as @Edheal mentions in another comment.

正如@Edheal在另一条评论中提到的那样。