Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

LINK TO THIS FORUM!

Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Feedback

"...your web site's great! I've been using this system for almost a year now and find it really, really helpful. The people have been helpful in answering just about any question you post in the forums..."

Geography

Where in the world do Tek-Tips members come from?

memory allocated within function and passed out of it

lehe (Programmer)
18 Jul 08 20:00
Hi,
I am asking for using "malloc" to allocate memory within a self-written function and then pass on to the outside of the function. I did it this way but guess that it might be the reason that caused run-time memory error. Could you please point out if it is wrong and give the correct way? Thanks in advance!

void main(){
int* ptr;
myfun(&ptr);
free(ptr);
}


void myfun(int**p){
int num;
// read the value of "num" from some file...
*p=(int*)malloc(num*sizeof(int));
}
cpjust (Programmer)
18 Jul 08 23:26
There are 2 things wrong with your code that I can see:

1.  There's no such thing as void main().  main() returns an int.  See:  http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044841143&id=1043284376

2.  You shouldn't cast malloc().  See:  http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1047673478&id=1043284351

Are you having any problems with the code now, or are you just wondering if it's correct?
lehe (Programmer)
19 Jul 08 10:04
Thanks for pointing out what I was not unware of.

Besides that, let's move back to my original question. Will it cause runtime memory error using "malloc" to allocate memory within a function and then pass on to its outside?
ArkM (IS/IT--Management)
19 Jul 08 10:34
Don't worry. You may use a pointer to allocated memory here, there and everywhere.
 

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close