Read:
and other questions on SO related to this question and other on world wide web, so continue reading...
Since soon, i figure, i never alloc
like this memory for char *
, but I thought it may work:
void _alloc(char *line)
*line = malloc(sizeof(char) * BUFSIZE);
Ignore error handler in _alloc
and main
. The main thing is SEGFAULT
on section like this:
main()
{
char *text, *start;
_alloc(text);
start = text;
// add contents in text briefly
*text++ = 'd'; *text = '\0'; // SEGFAULT
fprintf(stdout, "%s", start);
}
I had a picture that function _alloc working something like this:
main()
{
char *text;
/// function _alloc:
char *tmp = text;
*tmp = malloc ( sizeof(char) * BUFSIZE);
/// end
}
And... When i tried this, it give me warning: assignment makes integer from pointer without a cast and SEGF. My picture about it , is:
tmp = text; // tmp point at address of line
*tmp = malloc(...); // tmp change to what point line...
And i saw that i need in _alloc( char **) , and can't figure how it works with **. I tried to manipulate with array[][], i know it. But can't get picture, why it need to be char **? Here is part of answer:
Here,
line
is a local variable within_alloc
. Pointers are passed by value in C, so a receives a copy of the pointer in main when you do_alloc(text);
< answer user nos (modified with my name of variables) on Scope of malloc used in a function
P.S. i know that is simpler to write function like this char *_alloc();