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?

4
  • 1
    FYI: Don't cast the result of malloc. Commented Jan 31, 2014 at 20:04
  • @Barmar: Why not? In c++, you are even forced to cast the return-value. I think there is no problem with casting. Commented Jan 31, 2014 at 20:05
  • maja: stackoverflow.com/questions/605845/… Commented Jan 31, 2014 at 20:09
  • @Barmar: Thanks, I never tought about it in this way :) Commented Jan 31, 2014 at 20:11

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

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.