Reputation: 2184
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.
Upvotes: 1
Views: 39
Reputation: 25908
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.
Upvotes: 2