0

I try to free the memory of pointer to chars array. I didn't get error but when i check with Dr.Memory i have :

      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)

My Code:

    #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;
    }
3
  • The C standard specification says that fflush(stdin) is undefined behavior. While some libraries allow it as an extension don't do it if you want to be portable. And don't, ever, use gets to read a string. It's dangerous, was deprecated in the C99 standard, and removed completely from the C11 standard. Commented Mar 30, 2016 at 6:34
  • 1
    You forgot to free p_Array Commented Mar 30, 2016 at 6:36
  • And on another unrelated note, you do know that e.g. *(p_Array + i) is the same as p_Array[i]? Commented Mar 30, 2016 at 6:36

1 Answer 1

1

You're using the wrong loop bound for this loop:

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

The loop should be:

for (int i = 0; i < players; i++)
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

..and free(p_Array)
Ouuu, Thank you ! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.