从指向字符数组的指针释放内存
Free memory from pointer to chars array
我尝试释放指向字符数组的指针的内存。
我没有收到错误,但是当我检查 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;
}
您为此循环使用了错误的循环绑定:
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++)
...
我尝试释放指向字符数组的指针的内存。 我没有收到错误,但是当我检查 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;
}
您为此循环使用了错误的循环绑定:
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++)
...