get size of malloc'd object

Andrew Koenig ark at alice.UucP
Tue Jun 24 12:23:14 AEST 1986


There is a very simple way to do this portably:

	struct chunk {
		unsigned size;
		char *mem;
	};

	struct chunk
	challoc (n)
		unsigned n;
	{
		struct chunk ch;
		ch.size = n;
		ch.mem = malloc (n);
		return ch;
	}

	void
	chfree (ch)
		struct chunk ch;
	{
		if (ch.mem)
			free (ch.mem);
	}

Now rewrite your program to deal with memory through chunk structures
instead of through simple pointers.  It should be possible to make this
easier by using macros.



More information about the Comp.unix mailing list