1

I am having a problem with understanding the concept of dynamic memory allocation, I have some code that is encountering a segfault perhaps some one may have some insight?

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


typedef struct tName
{
   char **stringA;
   int capacity;
} tName;

tName *createTName(int length);
tName *destroyTName(tName *l);

int main(void) {
    tName *ll = createTName(10);
}

tName *createTName(int length) {
    tName *temp;
    int i;
    temp->capacity = length;

    temp->stringA= (char**) malloc(sizeof(char*) * length);
    for(i=0;i<length;i++)
       temp->stringA[i] = (char*) malloc(sizeof(char)*50);

    return temp;
}

When I call run this program I get a segfault, can anyone assist me please?

cat
  • 91
  • 10

1 Answers1

4

Your problem is here:

temp->capacity = length;

You are asigning a value to a variable, which doesn't have memory yet. You have to allocate memory for the struct to.

Use this:

tName *temp = malloc( sizeof(tName) );

If you only write tName *temp, the compiler will only allocate 4 Bytes (or 8 in 64bit Systems) for the pointer. But it wont't allocate the momory, where the pointer is pointing to.

Another problem is at the malloc, which allocates memory for the string - it should be this:

temp->stringA = malloc(length+1);

Fist of all, you don't have to multiply it with sizeof(char*) (which will again be 4 or 8 Bytes), but with sizeof(char). The Variabletype char always needs 1 Byte, so you don't have to mulitply it at all.

But you must not forget to allocate one extra-byte for the string, if you want to use string-operations. This byte is needed to stroe the Ascii-0, which specifies the end of the string.

If you forget about this byte, the Program can result in strange output, and even in sefgaults.

And about this loop:

for(i=0;i<length;i++)
       temp->stringA[i] = (char*) malloc(sizeof(char)*50);

I don't really know what you want to achieve with it, can you add some more information?

maja
  • 17,250
  • 17
  • 82
  • 125