473,785 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return of pointer

Hello,
If my function return a pointer on a memory area, where do I free it?
e.x.:
char *foo()
{
char *p;
p = malloc(10);
strcpy(p, "something" );
return(p);
}
void bar()
{
char *p = foo();
printf("%s", p);
free(p);
}
But force anybody to calling free() after use foo() not elegant solution,
for my mind... How can I avoid posible memory leaks if somebody forget to
call free()?

Thanks a lot!
--
Sergey Koveshnikov.
Nov 13 '05 #1
19 11191
In article <bo**********@d cs.eurocom.od.u a>, Sergey Koveshnikov wrote:
Hello,
If my function return a pointer on a memory area, where do I free it?
e.x.:
char *foo()
{
char *p;
p = malloc(10);
strcpy(p, "something" );
return(p);
}
void bar()
{
char *p = foo();
printf("%s", p);
free(p);
}
But force anybody to calling free() after use foo() not elegant solution,
Maybe not, but as long as you are consistent and document the
interface it works well.
for my mind... How can I avoid posible memory leaks if somebody forget to
call free()?


You can't force someone to remember to call free().

Creating a foo_alloc() and a foo_free() function might help
though (untested):

#include <stdlib.h>
#include <stdio.h>

int foo_alloc(char **p)
{
/* sanity checks of *p here */

*p = malloc(10);
if (*p == NULL) return 1;
strcpy(*p, "something" );
return 0;
}

int foo_free(char **p)
{
/* sanity checks of *p here */

free(*p);
*p = NULL;

return 0;
}

void bar()
{
char *p;

foo_alloc(&p);
printf("foo: %s\n", p);

foo_free(&p);
}


--
Andreas Kähäri
Nov 13 '05 #2
i.e. No way to do automatic cleanup dynamic allocated memory, if it's
unnecessary anywhere, except context of 'bar()', isn't it?
--
Sergey Koveshnikov.
Nov 13 '05 #3
In article <bo**********@d cs.eurocom.od.u a>, Sergey Koveshnikov wrote:
i.e. No way to do automatic cleanup dynamic allocated memory, if it's
unnecessary anywhere, except context of 'bar()', isn't it?


There is no built-in garbage collector in C, no.

--
Andreas Kähäri
Nov 13 '05 #4
But, what can I do if some foreign code expect from my function that it will
return char*, and it doesn't call free()? Do you know any 'save string'
library for ANSI C that provide self-destroyed strings?
May be it's possible to solve this problem with macros or 'static' type?

PS. Sorry if my questions are stupid, I'm new in the C.
--
Sergey Koveshnikov.
Nov 13 '05 #5
Sergey Koveshnikov <ac*****@euroco m.od.ua> wrote:
Hello,
If my function return a pointer on a memory area, where do I free it?
e.x.:
char *foo()
{
char *p;
p = malloc(10);
strcpy(p, "something" );
return(p);
}
void bar()
{
char *p = foo();
printf("%s", p);
free(p);
}
But force anybody to calling free() after use foo() not elegant solution,
for my mind... How can I avoid posible memory leaks if somebody forget to
call free()?


Maybe it's a good idea to adopt the bevaviour of, for example, the
standard library string functions, and let the caller take the full
responsibility for memory allocation/deallocation. E.g.:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BIG_ENOUGH 50

char *foo( char *p )
{
if ( p != NULL )
strcpy( p, "something" );
return( p );
}

int main( void )
{
char *p = malloc( BIG_ENOUGH );
if ( foo( p ) != NULL )
printf( "%s\n", p );
free( p );
return 0;
}

Note: you may want foo() to take an additional argument specifying the
buffer size, in order to avoid buffer overflows.

OTOH, if you, for example, want to imitate the non-standard strdup
function, you of course have to allocate the memory inside the function,
document the behaviour and hopefully the user of the function will get
it right.

HTH
Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #6
In article <bo**********@d cs.eurocom.od.u a>, Sergey Koveshnikov wrote:
But, what can I do if some foreign code expect from my function that it will
return char*, and it doesn't call free()? Do you know any 'save string'
library for ANSI C that provide self-destroyed strings?
May be it's possible to solve this problem with macros or 'static' type?

PS. Sorry if my questions are stupid, I'm new in the C.


You, as a library implementor, are not required to make sure
that the users of the library writes correct code.

Document the correct usage (whether to explicitly free() storage
or to call a special cleanup function), and that's the end of
your troubles.

It is possible to return a pointer to a static array, but you
will have to make sure that you point this out to the library
user as well, so that he/she doesn't wander off and tries to
free() that pointer, or so that he/she doesn't store its value
somewhere and gets confused when the data it points to suddenly
changes after the next call to your function.

My favourite solution is to provide two functions; one for
allocation and one for deallocation. This is a bit too involved
if it's just a question of a simple string and not a struct or
some opaque data type.

--
Andreas Kähäri
Nov 13 '05 #7
In <bo**********@d cs.eurocom.od.u a> Sergey Koveshnikov <ac*****@euroco m.od.ua> writes:
Hello,
If my function return a pointer on a memory area, where do I free it?
e.x.:
char *foo()
{
char *p;
p = malloc(10);
strcpy(p, "something" );
return(p);
}
void bar()
{
char *p = foo();
printf("%s", p);
free(p);
}
But force anybody to calling free() after use foo() not elegant solution,
for my mind... How can I avoid posible memory leaks if somebody forget to
call free()?


This is a perfectly valid approach. No matter where the memory is
dynamically allocated, someone may forget to release it. This is an
intrinsic issue with dynamically allocated memory.

The alternative is to pass to foo the address of the buffer. If the
buffer was not dynamically allocated, no need to release it:

#define STRING "something"

void foo(char *p)
{
strcpy(p, STRING);
}

void bar()
{
char p[sizeof STRING];
foo(p);
printf("%s\n", p);
}

Of course, this doesn't work if only the called function can evaluate
the size of the buffer.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #8
Sergey Koveshnikov wrote:
Hello,
If my function return a pointer on a memory area, where do I free it?
e.x.:
char *foo()
{
char *p;
p = malloc(10);
strcpy(p, "something" );
return(p);
}
void bar()
{
char *p = foo();
printf("%s", p);
free(p);
}
But force anybody to calling free() after use foo() not elegant solution,
for my mind... How can I avoid posible memory leaks if somebody forget to
call free()?

Thanks a lot!


Sergey...

You may be able to write a wrapper for malloc() that keeps a list
of all allocations it makes, then write a function to call free()
for each of the allocations in that list. Refine as necessary.

--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c
Read my lips: The apple doesn't fall very far from the tree.

Nov 13 '05 #9
On 2003-11-04, Sergey Koveshnikov <ac*****@euroco m.od.ua> wrote:
Hello,
If my function return a pointer on a memory area, where do I free it?
e.x.:
char *foo()
{
char *p;
p = malloc(10);
strcpy(p, "something" );
return(p);
}
void bar()
{
char *p = foo();
printf("%s", p);
free(p);
}
But force anybody to calling free() after use foo() not elegant solution,
for my mind... How can I avoid posible memory leaks if somebody forget to
call free()?

Thanks a lot!


You can design a callback interface to someone that wants the
memory:

void foo(void (*cb)(char *))
{
char *p = malloc(10);
if (p)
strcpy(p, "something" );
cb(p);
free(p);
}

void mycallback(char *p)
{
printf("%s", p);
}

void bar(char *p)
{
foo(mycallback) ;
}

-- James
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2046
by: Gama Franco | last post by:
Hi, I'm designing an interface for a shared library, and I would like to know if there is a standard about how to return an object to the user. I will use exceptions to report errors, so there are at least four ways to do it. For example if we have a method named M, that receives a reference to parameter p and returns object o.
5
3047
by: Neal Coombes | last post by:
Posted to comp.lang.c++.moderated with little response. Hoping for better from the unmoderated groups: -------- Original Message -------- Subject: Return appropriately by value, (smart) pointer, or reference Date: 27 Aug 2005 15:13:23 -0400 From: Neal Coombes <nealc@trdlnk.com> Organization: Aioe.org NNTP Server To: (Usenet) Newsgroups: comp.lang.c++.moderated
14
2708
by: William Ahern | last post by:
is this legal: FILE *func(void) { extern int errno; return (errno = EINVAL, NULL); } my compiler (gcc 2.9.x on openbsd) is complaining that i'm returning a pointer from int w/o a cast. gcc 3.x on linux, however, never made a peep
10
2620
by: LaEisem | last post by:
On-the-job, I have "inherited" a lot of old C language software. A question or two about when "casting" of null pointer constants is needed has occurred during behind-the-scenes cleanup of some of that software. That subject seems not to be addressed, at least not directly, in the C FAQ where FAQ 5.2 seems most relevant. References: * C FAQ 5.2 Null pointers (Including conditions where "casting" of null pointer...
4
157996
by: Isaac | last post by:
Hi mates I want to know a simple program of return array from function ? Do I need to use pointer to return the address of the first element in an array. Isaac
23
3615
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
4
6954
by: msolem | last post by:
I have some code where there are a set of functions that return pointers to each other. I'm having a bit of a hard time figuring out the correct type to use to do that. The code below works but I'm defining the functions as void*, and then casting when I use them. This code is going into a general purpose framework, and it would be much nicer if the user didn't need to do any casting. Can someone tell me how to set up those typedefs...
32
69698
by: zl2k | last post by:
hi, c++ user Suppose I constructed a large array and put it in the std::vector in a function and now I want to return it back to where the function is called. I can do like this: std::vector<int> fun(){ //build the vector v; return v; }
18
4064
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
9
3810
by: Francois Grieu | last post by:
When running the following code under MinGW, I get realloc(p,0) returned NULL Is that a non-conformance? TIA, Francois Grieu #include <stdio.h> #include <stdlib.h>
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10097
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9957
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.