0

I expect the following code to work. It compiles (gcc), but the executions gives Segmentation fault: 11. How come? Thanks

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

#define MAX_INDEX_LENGTH 20

main()
{
    char **indici;
    int n = 4;

    indici = (char **)malloc(n * sizeof(char*));
    int i;
    for (i = 0; i < n; i++)
    {
        indici[i] = (char *)malloc(MAX_INDEX_LENGTH * sizeof(char*));
    }

    strncpy(indici[0], "aaa", MAX_INDEX_LENGTH);
    strncpy(indici[0], "bbbb", MAX_INDEX_LENGTH);
    strncpy(indici[0], "ccccc", MAX_INDEX_LENGTH);
    strncpy(indici[0], "ddddddd", MAX_INDEX_LENGTH);

    for (i = 0; i < n; i++)
    {
        printf("Index %d is %s\n", n, indici[n]);
    }
}
1
  • Helpful answers have been posted yet, but I want to point out that you are allocating MAX_INDEX_LENGTH * sizeof(char*) instead of MAX_INDEX_LENGTH * sizeof(char) which is what you actually want I guess. Commented Jan 28, 2012 at 13:22

2 Answers 2

2

You're not populating all the elements, only indici[0] so they remain uninitialized and likely point to garbage. So when the second for runs it will dereference uninitialized stuff.

Maybe you meant:

strncpy(indici[0], "aaa", MAX_INDEX_LENGTH);
strncpy(indici[1], "bbbb", MAX_INDEX_LENGTH);
strncpy(indici[2], "ccccc", MAX_INDEX_LENGTH);
strncpy(indici[3], "ddddddd", MAX_INDEX_LENGTH);

A second problem is that you're trying to print indici[n], which is outside the allocated memory. You probably meant

printf("Index %d is %s\n", i, indici[i]);

Another subtler problem is this:

(char *)malloc(MAX_INDEX_LENGTH * sizeof(char*));
                                         ^^^^^^

You're allocating more than you need. You need to allocated a number of chars, so it should be sizeof(char). But sizeof(char) is always 1 so it should be:

malloc(MAX_INDEX_LENGTH);
Sign up to request clarification or add additional context in comments.

1 Comment

Try to run this, it will crash too. OP has problem in last loop.
1

You're copying all of the strings into indici[0], so the other 3 are uninitialized.

When you print the uninitialized ones, kaboom.

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.