UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C++
  • » Variable Declaration!

#1 2006-04-18 06:16 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

why cant we declare a (static) variable inside the case of a switch? I saw that a pointer variable declaration is possible inside a case. why is this so? When we declare a pointer variable whether any memory is allocated (Atleast the memory to hold the address)? Please clarify me.

Offline

#2 2006-04-18 03:42 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

int main(int argc, char* argv[])
{
	switch (argc){
		case 0: {
			static int t;
			t = argc;
			break;
		} case 1: {
			char* s;
			s = argv[0];
			break;
		}
	}
	return 0;
}

I think you forgot to add the blocks within the case statements. Switch statements are just a bit weird, so they're needed if you want to declare new variables. Just like the break things, live with it and don't wonder too much about the whys or whatifs (basically variable declarations aren't possible).

I don't understand your second question though...

Offline

#3 2006-04-18 07:58 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,847
Website

Re: Variable Declaration!

i3839 is right for C...  But, this is posted in the C++ forum...  Are you really using a
C++ compiler or a straight C compiler??

For C++, I'm pretty sure you're allowed to declare new variables anywhere
intermixed with code, rather than being restricted to the start of a code block, as
with C...  (Though, I think that's hellishly ugly, and one of the things I hate about
C++...  One of the MANY things... ;-))

Yep, stripping the curly braces from the above cases, g++ will happily compile it
without complaint...

Offline

#4 2006-04-18 10:16 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

It isn't just that, gcc will compile it happily when there are declarations after the switch statement. It seems that although modern C allows declarations in the middle of the code, it doesn't go as far as allowing declarations in a code part that isn't always taken at runtime.

(C++ forum you say? Well, yes, now you mention it, perhaps it is. Maybe I'm lost or something... ;-)

Offline

#5 2006-04-19 04:56 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

Yes I am working with C++. But when I declared without braces it shown some strange compiler errors.

switch(ethertype)
 {
  case 0x800:
      IPvFour ipv4;
      break;
  default:
      cout<<endl;
      break;
 }

this shows the following error (I am using KDevelop)


/Ethernet.cpp:45: error: jump to case label
/Ethernet.cpp:43: error: enters scope of non-POD `IPvFour ipv4'
*** Exited with status: 2 ***
But with braces it worked fine!
Thankyou i3839.

My second question is pointers are mainly meant for dymanic memory allocation know, when we declare a pointer variable how much memory will be allocated?
eg char *c ;
or  int *ptr;

Offline

#6 2006-04-19 11:13 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

A pointer is just a pointer, nothing more. It's just a number which happens to be a memory address most of the time. Think of it like a long integer. But using bare pointers would be like using void pointers everywhere, to add some safety they added the type the pointer points to in the declaration, so the compiler can do more checks. When declaring a pointer it will always take sizeof(void*) memory, 32 bits on 32 bit systems and 64 bits on 64 bits systems.

Offline

#7 2006-04-20 04:38 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

Thank you very much, This reply is satisfactory for me.

one more thing, What happens when we call a method (member function) from a constructor??
(There is no compiler error)

But this code causes segmantation fault at run time, can you guess what is happening?

#include<iostream>
using namespace std;
class linkedlist
{
 private:
   struct list
   {
    int val;
    struct list *next;
   };
   struct list *node,*head;
   
 public: 
   linkedlist();
   int add(int val);
};

linkedlist::linkedlist()
{
 cout<<endl<<"staritng";
 node->next=NULL;
 cout<<endl<<"Ending";
 cout<<endl;
 head=NULL;
}

int linkedlist::add(int val)
{
 node->val=val;
 node->next=new list;
 if(head==NULL)
  head=node;
 node=node->next;
 return 0;
}


int main()
{
 linkedlist objlist;
 objlist.add(10);
 return 0;
}


whether the above one is good idea to implement linked list in c++?
Thanking you,
       Lloyd.

Offline

#8 2006-04-20 01:51 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

Well node->next=NULL; won't work. 'node' is just a pointer, but it doesn't point to anything yet. It appears that you want struct list node; instead of a pointer to a struct list, then it won't crash there. Either that, or allocate a struct list in your constructor, or let the pointer be given as a parameter to the constructor.

As for if it's a good implementation for linked list in C++: Probably not, for two reasons. First one is that C++ already has a vector implementation which probably does what you want already, failing that, there is most likely another STL class which does exactly what you want. The second reason is more important, and that is that it seems you want to store a list of numbers. Now I don't know how your list is going to be used, but if you want to look things up then a list is very inefficient. If you only walk the whole list to get all numbers and using them all, then it's fine to use a list. But if you e.g. want to check if a number already exists in the list then you porbably can use something more efficient for searching like a tree. I can't think of a reason why I would want to have a list of just numbers, its use seems very limited. (Though all this isn't related directly to the list implementation itself, which as it is isn't a list yet. ;-)

I'm not sure what that add function is trying to do, it overwrites the old value of val or what? If not, then why isn't the int value a parameter to the constructor? Though if this is the whole list then why do you keep an unused struct list around? I'm confused. I'd expect something like the following:

void linkedlist::add(int val)
{
	struct list* n;

	n = new list;
	n->val = val
	n->next = head;
	head = n;
}

Offline

#9 2006-04-20 03:46 PM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

Your  reply seems very useful for me.
  It is just a simplified version what I wanted to do. Yes, I will be needing lot of searches, I too prefer to use trees. But what I feel as problamatic is, if I write it (tree) using recursion stack may get overflo. If I use the other way the code become so complex to manage (Tree balancing - To get the best benefit). what is your openion? (I understood the flaws in my code as well, thank you).

What will really happen if we call a member function from the constructor?

Offline

#10 2006-04-20 04:31 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

Offline

#11 2006-04-20 09:21 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,847
Website

Re: Variable Declaration!

And, instead of reinventing the wheel (unless you really WANT to just for the
experience, which is fine), you might also see if your system has standard library
functions (or classes, since this is C++) for handling those items...  (I can't speak
for C++, but glibc has tsearch() and friends, which do a very decent self-balancing
red/black tree...  As long as you don't mind it dynamically allocating node space...  If
you have tight memory requirements, you'll probably have to code up your own...  It's
not too horrible...  I just recently had to do so myself, in a situation where I needed it
to use a specifically sized pre-allocated buffer for all node and record space...  The
main red/black balancing when adding a new node is fairly easy; the real ball-buster
is handling deletions...  If you can avoid deleting nodes, that'll save you a lot of
headaches...  If you must handle deletions, well then it's still doable, but a lot more
twisted... ;-)  And, in any event, you can handle all necessary tree operations
(including in-order traversal!) completely free of recursion, and with relatively trivial
code, as long as you include an "up" or "parent" pointer in your nodes...  Without
that, you can still avoid recursion, but the code becomes a lot uglier...  I've looked
at the glibc tsearch() code, and it uses the ugly way... ;-)  I just don't think the
savings of an extra pointer per node is worth the added code complexity, but your
needs may vary...)

Offline

#12 2006-04-21 07:39 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

Yes, I have desided to use tree, but if I use AVL or red/black tree things become unmanagable. The problem is this -
In a tree node (Eg. Binary tree) we must have a key field for making the comparison (In searching). In my case by using the key field only we can identify the node uniquely but as the node is found the key field also has to be modified to a new value. So the fundamental principle ( left child key must be less than root node key, right child must be greater than root node) of binary tree could be broken when the updation is done. Then I have to balance the whole tree again! (It will be a big problem,isn't it?). (I dont have any other uniquely distinguishable key field).

How can I solve this problem? If I use a linked list this is not going to be a problem but the searching time is key factor in my application! (Searching is done very frequently!)

Offline

#13 2006-04-21 10:28 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

I'd make a simple wrapper for whatever data structure you're going to use. Then first implement something as simple as possible in little time (e.g. use an existing library implementation) and finish the rest of your program. Then when that's done you can actually measure which solution is better and which not for your program.

If a value is modified you don't have much other choice than to remove the value from the tree and add the new one. That's a O(log n) operation in balanced trees.

Offline

#14 2006-04-21 10:32 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

The second thing seems to be useful for me. I shall delete the node and reinsert it. There is no other way for me to make use of a tree. Thanks!

Offline

#15 2006-04-24 05:39 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

I have been thinking about the solution for the following problem

As an example, I have 100 bytes of data. In the first phase I verify the first 20 bytes using a class and its functionalities and based on the result I have to make the object of next class. (This object may vary based on the result).This object has to do some operations on a part of the remaining 80 bytes. (But the size of part also varies from object to object). Then this object has to create another object and this process continues until the 100 bytes are finished. How can I do this?

Making a direct pointer from each class to the data? (Is this a good idea, when we consider data secutiry, modification and enhancement of the application...?)

Or do I have to copy the data from each object to the other? (Thus first class will hold 100 bytes, second one will have the remaining 80 bytes, third one will have some 50 or 60 bytes etc..)

If you are not getting clear, the actual problem is I am writing a network packet analyzer. So when we process from the lower layer protocols only we will understand what is the next higher layer protocol. So based on the next layer protocol we have to make the object and process it. For each protocol the data size also varies. Though there are hundreds of protocols there is no doubt about adding new protocols in each layer.

What is your openion regarding this??

(Thanks, Lloyd)

Offline

#16 2006-04-24 01:57 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

The first class gets a pointer to the data, knows how much of it is his, and does whatever is needed with it (those 20 first bytes in your example). When it did its thing in some way is figured out which class should handle the remaining data. That class gets the pointer to the 21th byte and the cycle repeats. But this is more or less the same what you said, so I think I miss what your problem actually is.

Of course you're parsing arbitrary data, so it should be done safely to avoid exploits.

Offline

#17 2006-04-24 02:06 PM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

What I am trying to explain is the data is interms of kilobytes. So copying data from one object to another will eat up lot of memory. I am worrying about the memory wastage as well as the data security. which way to be preferred?

Offline

#18 2006-04-24 02:38 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

No copying is needed, you only have to pass pointers around, really. As long as each class only modifies the part it's handling and leaves the rest untouched then I don't see any problem, nor a need for copying. Depending on how your program is organized memory handling may be slightly tricky, e.g. if it's unclear when the package is processed or if the objects stay alive longer than the package. But even copying a bunch of kilobytes isn't going to kill performance in itself, especially not when it means you can free up the package sooner. But if it simplifies thing and is easier to implement, then just do the copying and only worry about it if it shows up in the profiles.

Offline

#19 2006-04-24 03:10 PM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

Ok, now am dealing with it in terms of copying, though I worry about data security. Let us see what happens. Your words gave me confidance to go further. Thank you!

Offline

#20 2006-04-25 10:11 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

But if I try to access a private pointer in a class from another class, wont it cause data security problem??

Offline

#21 2006-04-25 11:05 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

Eh, that isn't needed and ugly like hell. I liked your previous post more. ;-)

I think we've a misunderstanding somewhere, if you thought that's needed at all.

Offline

#22 2006-04-27 10:18 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

Offline

#23 2006-04-27 01:09 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,847
Website

Re: Variable Declaration!

I'm not sure I get the problem...  You're saying you realloc() these buffers periodically
and add new data?  Ok, that shouldn't be a problem, unless you're doing something
else problematic...  Such as maintaining another reference to the old buffer contents
or something...  Eg: if you had some other pointers somewhere pointing into these
buffers, those would all be rendered invalid every time you do realloc(), since that
may very well change the location of the buffer completely...  That's my only guess
as to what your problem might be, unless you're otherwise trashing memory by
writing off the end of the buffer, or something...

But, if you intend these buffers to grow to some maximum size before dumping them
to file, why not simply use large fixed-sized buffers of that max size, rather than
screw around with realloc()'ing the things every time new data arrives??  That'd
seem to me to be a lot easier approach, as well as a lot more efficient (those
repeated realloc()'s aren't cheap, especially when it has to move the buffer to a
completely new location)...  Yes, it means taking up the max amount of memory
right from the start, but if you're going to grow upto that amount before dumping
to file anyway, so what?  I don't see any reason not to take it all now, rather than
slowly grow upto that much... *shrug*

Offline

#24 2006-04-27 01:53 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Variable Declaration!

Just two things I want to point out:

1) Valgrind is very useful for such things like this.

2) The kernel already does caching, so write() isn't touching the hardddisk at all, that's done later on. So if I were you I wouldn't worry about it much and just write it each time. If you use stdio functions then here is libc is probably also caching stuff.

Offline

#25 2006-04-28 04:46 AM

Lloyd
Member
Registered: 2006-02-13
Posts: 53

Re: Variable Declaration!

Thank Rob and i3839. Solved the problem, it was with the realloc. After the realloc I was trying to refer some invalid memory. (the memory which is being used before the reallocation).

As i3839 said if the kernel does caching why should I go for these buffer and all.
Thanks again,
    Lloyd.

Is there is any possibility for malloc to fail in an OS?

Though if the required memory is not available, wont the OS does the necessary page replacements and allocate the requested memory?

Offline

  • Index
  • » C++
  • » Variable Declaration!

Board footer

Powered by FluxBB