This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

void pointer and map (fwd)


Oops! I forgot to mention version:

Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/3.2.3/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man 
--infodir=/usr/share/info --enable-shared --enable-threads=posix 
--disable-checking --with-system-zlib --enable-__cxa_atexit 
--host=i386-redhat-linux
Thread model: posix
gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-20)


-- 
Regards,
Anitha B
@S A N K H Y A

---------- Forwarded message ----------
Date: Fri, 21 Dec 2007 18:30:21 +0530 (IST)
From: Anitha Boyapati <anithab@sankhya.com>
To: gcc-help@gcc.gnu.org
Subject: void pointer and map


Hello,

Below is a minimisation of a larger program (that may explain why the 
objective of the progarm is not too clear). The essence is I am trying to 
do a map find with a structure as key and the significant aspect of the 
structure is - it has a void *. I expect the below progarm to print 
nothing as s2 is not there on the map at all! There are 2 findings 
however:

 1. "Address found" is getting printed
 2. Segmentation fault occurs.

For convenience, I am attaching the code as well.
------------------------------------------------------------------------
#include <iostream>
#include <map>

using namespace std;

struct Value {
	int id;
	void *buf;
	Value (long l) { id = 4; buf = operator new(128); 
		          long *c = reinterpret_cast<long *>(buf);
		    	  *c = l;
		  	}
	~Value() { operator delete(buf); }
}; 

bool operator< (const Value &v1, const Value &v2) {
	bool result = (*(reinterpret_cast<long *>(v1.buf))) < (*(reinterpret_cast<long *>(v2.buf)));
 	return result;
}

bool operator== (const Value &v1, const Value &v2) {
	bool result = (*(reinterpret_cast<long *>(v1.buf))) == (*(reinterpret_cast<long *>(v2.buf)));
 	return result;
}

typedef map<Value, string> Map;
typedef Map::iterator ITR;

int main() {
	Map m;
	ITR itr;

	Value s((long)10); 
	m.insert(Map::value_type(s, "1"));
 
	Value s2((long)20);

	itr = m.find(s2);
	if(itr != m.end()) {
		cout << "Address found!" << endl;
	} 
}

		*****
What is further interesting is it does not work with any of pointers 
(e.g char *buf) but does well with non aggregate types (e.g long buf).
This explains I am probably missing something grossly. Any advice helps.
BTW, it would be interesting to see the cause of segmentation fault too 
which happen to be common in all the cases.

Thanks in advance,

-- 
Regards,
Anitha B
@S A N K H Y A


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]