【问题标题】:Free memory from pointer to chars array从指向 char 数组的指针释放内存
【发布时间】:2016-07-18 00:18:45
【问题描述】:

我尝试释放指向 chars 数组的指针的内存。 我没有收到错误,但是当我检查 Dr.Memory 时,我有:

      1 unique,    13 total unaddressable access(es)
      0 unique,     0 total uninitialized access(es)
      1 unique,     1 total invalid heap argument(s)
      0 unique,     0 total GDI usage error(s)
      0 unique,     0 total handle leak(s)
      0 unique,     0 total warning(s)
      1 unique,     1 total,      8 byte(s) of leak(s)
      0 unique,     0 total,      0 byte(s) of possible leak(s)

我的代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define SIZE_NAME 20

    int main(void)
    {
        int players, i, j;
        char** p_Array = NULL;
        char name[SIZE_NAME];

        printf("Enter number of players in basketball: ");
        scanf_s("%d", &players);

        p_Array = (char**)malloc(sizeof(char*) * players); // array with [players] cells.
        for (int i = 0; i < SIZE_NAME; i++)
            *(p_Array + i) = (char*)malloc((SIZE_NAME + 1) * sizeof(char));

        for (i = 0; i < players; i++)
        {
            printf("Enter name for player number %d: ", i + 1);

            fflush(stdin); // clear buffer
            gets(name);
            strcpy(*(p_Array + i), name);
        }


        for (i = 0; i < players; i++)
        {
            printf("Name of player number %d is %s \n", i + 1, *(p_Array + i) );
        }

        for (i = 0; i < players; i++)
            free(*(p_Array + i)); // delete the array from the RAM. 
        getchar();  
        return 0;
    }

【问题讨论】:

  • C 标准规范说fflush(stdin)未定义的行为。虽然有些库允许它作为扩展,但如果您想要可移植,请不要这样做。并且永远不要使用gets 来读取字符串。它很危险,在 C99 标准中已被弃用,并从 C11 标准中完全删除。
  • 你忘记释放p_Array
  • 在另一个不相关的说明中,您确实知道,例如*(p_Array + i)p_Array[i] 一样吗?

标签: c pointers memory malloc free


【解决方案1】:

您为此循环使用了错误的循环:

for (int i = 0; i < SIZE_NAME; i++)
    *(p_Array + i) = (char*)malloc((SIZE_NAME + 1) * sizeof(char));

循环应该是:

for (int i = 0; i < players; i++)
    ...

【讨论】:

  • ..和free(p_Array)
  • 哎呀,谢谢! :)
猜你喜欢
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 2021-01-26
  • 2014-09-05
相关资源
最近更新 更多