1
void retsom(char **page)
{
    *page = (char*) malloc(sizeof(char) * 10);
    *page[0] = 'a';
    *page[1] = 'b';
}
void main()
{
    char *page = NULL;
    retsom(&page);
    printf("%c %c",page[0],page[1]);

}

This code is giving segmentation fault. Its gives segmentation fault at *page[1] = 'b';

I want to pass a array to function and modify its content.

8
  • Sorry, silly mistake. Got the error. I have to change *page[0] = 'a' to (*page)[0] = 'a'. Seems like associativity issue. Commented Mar 12, 2015 at 11:46
  • Whenever you are unsure, you should look up the C Operator precedence, en.wikipedia.org/wiki/… Commented Mar 12, 2015 at 11:54
  • 1
    @saurabhagarwal ,Post that as an answer. Commented Mar 12, 2015 at 11:56
  • 1
    The page is uninitialized, you set the first 2 bytes, but do not add a final '\0'. It would be safer to use *page = calloc(10, sizeof **page); Commented Mar 12, 2015 at 12:10
  • 1
    retsom allocates 10 chars with malloc. These chars are uninitialized and may contain random values. retsom only initializes the first 2 chars to 'a' and 'b', leaving the rest in a random state. This is error prone, leading to spurious, non reproducible bugs. The cost of calloc versus malloc is negligible. The benefit is the initialization to 0 of the allocated memory block. Commented Mar 12, 2015 at 17:20

1 Answer 1

2

You're regularly going to come across problems like this if you confuse yourself with too much indirection. Much better is to change to:

void retsom(char ** page)
{
    char * newpage = malloc(10);
    if ( !newpage ) {
        perror("couldn't allocate memory");
        exit(EXIT_FAILURE);
    }

    newpage[0] = 'a';
    newpage[1] = 'b';

    *page = newpage;
}

and avoid the issue entirely. This also has the benefit that if you want to do something other than terminate in the event of malloc() or other failure, you haven't yet overwritten the pointer the caller supplied, so your function is better behaved in exceptional conditions.

Note that sizeof(char) is always 1 by definition, and therefore redundant, and that you shouldn't cast the return from malloc() in C. malloc() can also fail, so you should check its return value.

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.