Home > Software design >  Set the last value of a dynamic array of char pointers in C to NULL for while loop termination?
Set the last value of a dynamic array of char pointers in C to NULL for while loop termination?

Time:03-02

I have a few questions based off the code below.

  1. Would this be the correct way to have a sentinel value of NULL at the end of this dynamic array of char pointers? If not what could I do?
  2. Will the code below cause a memory leak because I am setting malloced memory to NULL?

My general question would be.

  1. What could I possibly do so that I can have a dynamic array of character pointers with the last value to be NULL so I can stop the loop at that point without keeping a count of how many elements in the dynamic array of character pointers.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i = 0;
    char **array_strings = NULL;
    array_strings = malloc(sizeof(char *) * 2);
    array_strings[0] = malloc(sizeof(char) * 5);
    strcpy(array_strings[0],"test");
    array_strings[1]=NULL;
    while (array_strings[i] != NULL)
    {
        printf("array_strings[%d]: %s", i, array_strings[i]);
        i  ;
    }
    free(array_strings[0]);
    free(array_strings[1]);
    free(array_strings);
    return 0;
}

CodePudding user response:

Would this be the correct way to have a sentinel value of NULL at the end of this dynamic array of char pointers? If not what could I do?

This is correct. You have an dynamic array of char pointers, with the last pointer being set to NULL. There is no mistake there.

Will the code below cause a memory leak because I am setting malloced memory to NULL

You are storing NULL in malloced memory, not setting any reference to the memory to NULL, so there is no memory leak. All pointers returned by malloc are freed.

  • Related