Search code examples
cdynamicallocation

adding and printing elements of ** pointer that is controlled by a pointer to a struct


I have a struct typedef to SmartArray that has a variable char **array. I have been trying to debug the code for several hours, and have made lots of progress. However, i'm stuck on this particular bug. I have a function to print said array out. It will print twice, and then on the third time it does not print at all! I have a feeling this has something to do with how I am adding malloc to an array being one one does not print out correct. For the last section of the array, it prints "Testing Na". Any ideas? I would appreciate the help.

Here is the part of the function I am suspecting is the cause, however, I can't seem to find it: //allocate min space for string

  printf("approaching malloc\n");
  strPtr = malloc( sizeof(char) * (strlen(str) + 1) );

  if(strPtr == NULL)
  {
    return NULL;
  }
  printf("made it past malloc!\n");
  strcpy(strPtr, str);
  //if crash probably this code
  smarty->array[index] = strPtr;

  if(smarty->array[0] == NULL)
  {
    return NULL;
  }



  return strPtr;

Here is my test code:

typedef struct SmartArray
{
    // We will store an array of strings (i.e., an array of char arrays)
    char **array;

    // Size of array (i.e., number of elements that have been added to the array)
    int size;

    // Length of the array (i.e., the array's current maximum capacity)
    int capacity;

} SmartArray;
        int main(void)
    {
        int i; char buffer[32];

        SmartArray *smarty1 = createSmartArray(-1);
        printf("Array created\n");

            // Print the contents of smarty1.
            printf("\n-- SMART ARRAY 1: --\n");
            printSmartArray(smarty1);
            printf("Made it past print!\n");
            put(smarty1,"Hi, my name is ");
            put(smarty1, "Hello, my name is");
            put(smarty1, "Testing Names");
            printf("made it past put!\n");
            printf("smart away is now\n");
            printSmartArray(smarty1);
            printf("end of main!\n");

I feel like it's something completely obvious I'm just overlooking because I am a novice.

Here's a picture of what i'm trying to get it to look like in memory: click here for memory diagram

UPDATE: I figured out why it wasn't printing all the names, but the program segfaults atfter the print function.


Solution

  • I think it is because you are trying to extend your array using malloc. A C array can only point to one block of storage at a time. When you use malloc it will allocate an entirely new block of storage and you are trying to add that on to the end of your array when you write smarty->array[index] = strPtr.

    If you want to extend the size of your C array, use realloc instead which will allocate a new, bigger block of memory for your array and copy the existing content to it as well.

    If that doesn't solve the problem can you post your entire put function?