473,394 Members | 1,718 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

[Q] Testing for malloc()

Hi all,

I've written some code to make a hash data structure and associated
funtions (insert, delete, search). In the delete function, I want to free()
the key and the associated value. But since I want to be able to use this
code, I can't discount the chance that the key or the value are static
values on the stack. If this is the case, then free() will (obviously) fail.

On Solaris <sys/ucontext.h> has a function stack_inbounds that will return
a non-zero value if the address passed to it is in the heap, but this
function isn't portable -- only Solaris implements it.

So the really short version of the question is: How can I test to see if a
pointer points to malloc() assigned space (on the heap) or is a static value
defined in the data stack?

Thanks in advance,
Ian

ro****@magma.ca

Nov 13 '05 #1
7 2496
I just thought I'd post some code to make my problem a little clearer:

test.c:

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

int main() {
char *foo_string;

/* Test to free malloc assigned space */

if ( ! ( foo_string = malloc ( sizeof (char) * 10 ) ) ) {
printf ( "Could not allocate space\n" );
exit ( 1 );
}

free ( foo_string );

/* Test to free a static string */

foo_string = "Random drivel";

free ( foo_string );

printf ( "Completed Successfully\n" );
exit ( 0 );
}
/* END test.c */

$./test
*** malloc[1147]: Deallocation of a pointer not malloced: 0x1ff0; This could
be a double free(), or free() called with the middle of an allocated block;
Try setting environment variable MallocHelp to see tools to help debug
Completed Successfully
$

The program completed successfully, but with ugly error messages and messy
code. Is there any test I can perform on foo_string to see if I can free()
it or not?

Thanks again,
Ian

On 8/27/03 6:18 PM, in article BB******************@magma.ca, "Ian Roddis"
<ro****@magma.ca> wrote:
Hi all,

I've written some code to make a hash data structure and associated
funtions (insert, delete, search). In the delete function, I want to free()
the key and the associated value. But since I want to be able to use this
code, I can't discount the chance that the key or the value are static
values on the stack. If this is the case, then free() will (obviously) fail.

On Solaris <sys/ucontext.h> has a function stack_inbounds that will return
a non-zero value if the address passed to it is in the heap, but this
function isn't portable -- only Solaris implements it.

So the really short version of the question is: How can I test to see if a
pointer points to malloc() assigned space (on the heap) or is a static value
defined in the data stack?

Thanks in advance,
Ian

ro****@magma.ca

Nov 13 '05 #2
> I've written some code to make a hash data structure and associated
funtions (insert, delete, search). In the delete function, I want to free()
the key and the associated value. But since I want to be able to use this
code, I can't discount the chance that the key or the value are static
values on the stack. If this is the case, then free() will (obviously) fail.
free() is not guaranteed to fail obviously. free() may fail in a
subtle manner that is maximally embarassing or expensive (e.g. it
only fails in front of the customer or the chairman of the board.
Or it only fails when it is in production and then it shuts down
the power grid in several states or scatters pieces of spacecraft
over hundreds of miles).
On Solaris <sys/ucontext.h> has a function stack_inbounds that will return
a non-zero value if the address passed to it is in the heap, but this
function isn't portable -- only Solaris implements it.
Functions like this can get, um, "interesting" when you try to use
threads. Of course, those aren't standard either.
So the really short version of the question is: How can I test to see if a
pointer points to malloc() assigned space (on the heap) or is a static value
defined in the data stack?


You invoke the wrath of undefined behavior.

if ((void)fflush(++(void)main++)) {
/* variable was allocated from the toilet */
} else {
/* variable was allocated from the garbage dump */
}
is one way to make it fail at compile time so you'll know right
away that it won't work. I'm not aware of a system-specific way
to do this other than the one you mentioned for Solaris, and
a system on which malloc() always fails.

Oh, yes, there's more choices than this. The pointer can point to
malloc() assigned space, it could point to an automatic variable
(what stack?), it could point to static data in the program, or it
could point to static data in a shared library (which often blows
to bits system-specific assumptions about the addresses of "the
beginning and end of the data segment"). ANSI C does not provide
for shared libraries but it doesn't prohibit them either.

Or you make sure that all of the values are, in fact, allocated
with malloc() by making copies yourself. This, obviously, involves
a change in strategy for the caller of your function for freeing
allocated memory once.

Gordon L. Burditt
Nov 13 '05 #3
Bad design. If the caller allocates the memory, the caller should free
it. But if you really want to do this, simply document that the caller
must use malloc().

Sam
Nov 13 '05 #4
Thanks very much. This is the solution I'll use. Thanks very much for
everyone's input.

-Ian

On 8/27/03 10:18 PM, in article
37**************************@posting.google.com, "Samuel Barber"
<op*****@yahoo.com> wrote:
Bad design. If the caller allocates the memory, the caller should free
it. But if you really want to do this, simply document that the caller
must use malloc().

Sam

Nov 13 '05 #5
And now I get to display my ignorance :). Is there an easy way to determine
the size of the memory pointed to by a pointer?

/* begin hash_test.c */

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

int hash_add_item ( struct Hash *hash_ptr, char *key, void* contents ) {
char *key_copy;
void *contents_copy;

printf ( "Creating new contents of %d bytes\n", sizeof ( *contents ) );
if ( ! ( key_copy = malloc ( sizeof ( *contents ) ) ) ) {
printf ( "There is insufficient memory\n" );
return 1;
} else {
/* copy contents to contents_copy here */
}
}

int main() {
struct Hash *hash_ptr;
char *key = "A key", *contents = "Random data";

hash_add_item ( hash_ptr, key, contents );
}

/* end hash_test.c */

$ gcc -o test hash_test.c ; ./test
Creating new contents of 4 bytes
$

I want to avoid getting the caller to calculate to the size of the pointers
they're passing if at all possible.

Thanks again,
-Ian
On 8/28/03 4:12 PM, in article BB******************@magma.ca, "Ian Roddis"
<ro****@magma.ca> wrote:
Thanks very much. This is the solution I'll use. Thanks very much for
everyone's input.

-Ian

On 8/27/03 10:18 PM, in article
37**************************@posting.google.com, "Samuel Barber"
<op*****@yahoo.com> wrote:
Bad design. If the caller allocates the memory, the caller should free
it. But if you really want to do this, simply document that the caller
must use malloc().

Sam


Nov 13 '05 #6
Ian Roddis wrote:

And now I get to display my ignorance :).
Is there an easy way to determine
the size of the memory pointed to by a pointer?

/* begin hash_test.c */

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

int hash_add_item ( struct Hash *hash_ptr, char *key, void* contents )

int hash_add_item ( struct Hash *hash_ptr, char *key,
void* contents, size_t contents_size )

--
pete
Nov 13 '05 #7
Ian Roddis wrote:

And now I get to display my ignorance :). Is there an easy way
to determine the size of the memory pointed to by a pointer?

/* begin hash_test.c */
.... snip ...
I want to avoid getting the caller to calculate to the size of
the pointers they're passing if at all possible.


You might want to examine the techniques used in hashlib (see:

<http://cbfalconer.home.att.net/download/> )

to handle this sort of thing. In general, only the caller can
possibly know the size of memory required to store his data, so
it should be his responsibility to allocate that memory.

--
Replies should be to the newsgroup
Chuck Falconer, on vacation
Nov 13 '05 #8

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

Similar topics

9
by: WL | last post by:
Hey, all. I'm creating an array of strings (char **argv style) on the fly, and using realloc to create string pointers, and malloc for the strings itself (if that makes any sense). I'm using the...
231
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought...
4
by: Scott Taylor | last post by:
I've searched through the FAQ but I can't find this problem, which seems like it should be a newbie one. Here is a following code sample, without the necessary testing of malloc, including of...
82
by: quiberon2 | last post by:
Hi, Sorry if it might be a stupid question but what should returns malloc(0) ? void *ptr = malloc(0); I am running gcc 3.3.5 and a non-null address is returned. ( in the compiler that I am...
71
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a...
34
by: niranjan.singh | last post by:
This is regarding to test an SDK memory stuff. In what situation malloc gets fail. any comment/reply pls.... regards
30
by: Alf P. Steinbach | last post by:
I once suggested in that SomeOne Else(TM) should propose a string value class that accepted literals and char pointers and so on, with possible custom deleter, and in case of literal strings just...
7
by: somenath | last post by:
Hi All , As a process of my C language learning I was trying to learn how malloc can be implemented from K&R2 .But I am not able to understand few points . It would be very much helpful if...
173
by: Marty James | last post by:
Howdy, I was reflecting recently on malloc. Obviously, for tiny allocations like 20 bytes to strcpy a filename or something, there's no point putting in a check on the return value of malloc....
25
by: jbholman | last post by:
I am pretty new to C and doing my first project in C. I actually read almost the entire FAQ, but can't seem to figure out this problem. I have a structure. I have a list of these structures. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...

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.