1836525 Members
3261 Online
110101 Solutions
New Discussion

Re: Calloc problems

 
Alex Lavrov
Regular Advisor

Calloc problems

i am doing an allocation of memory like that
: ptr = (char *) calloc (...,size) ;
when it done from main() everything is fine.
but if i call a sub function from the main ,
and allocate the pointer there , when i try to use the variable (ptr[0] = 'a')
i got segmentation fault.
as i mentioned before. it's only happen in a sub-function .
thanks for your help.
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor

Re: Calloc problems

I suspect that it a case of the variable becoming undefined upon function exit. Calloc, malloc, ... work just fine inside functions. If you will post a section of your code that illusrates the problem then I suspect the fix will be trivial.
If it ain't broke, I can fix that.
Adam J Markiewicz
Trusted Contributor

Re: Calloc problems

I hope you do not try:



void myalloc( char *ptr )
{
ptr = malloc( 100 );
}


int main( void )
{
char *ptr;
myalloc( ptr );
ptr[ 0 ] = 0;

return 0;
}



Good luck
Adam
I do everything perfectly, except from my mistakes
Don Morris_1
Honored Contributor

Re: Calloc problems

You need to pass the address of ptr from main to the subfunction if you want the updated value back in main. Which also means you need to have the allocation sub-function take char **.
Kenneth Platz
Esteemed Contributor

Re: Calloc problems

Your other option is something like this:

char *myfunc() {
char *p;

p=(char *)calloc( size );

/* Do some stuff with p */

return p;
}

int main() {
char *p;

p = myfunc();

/* now you can access p */
}


Hope this helps.
I think, therefore I am... I think!