I forget that what's 'obvious' to me is not to every one
We all do. :) For me, obvious now is not always obvious later too. ;)
I forget that what's 'obvious' to me is not to every one
We all do. :) For me, obvious now is not always obvious later too. ;)
The memory is on the heap, but the pointer you use to get to the memory is not. It follows the same rules as any other variable from the same scope. You can save the pointer by returning it from the function:
string* trArr(int transactions)
{
return new string[transactions];
}
There are different iterator categories. The iterators for a vector are the most flexible and they are called random access iterators. Lists use bidirectional iterators, and those do not support comparing with less.
You shouldn't have to compile it to see that it will crash.
All I see is undefined behavior from using a bogus pointer. I have debugged many cases where the same problem does not crash, so your theoretical result does not mean anything unless you can back it up with empirical data. The problem is that saying things like this will crash gives beginners a false sense of security that the program will fail spectacularly if they do something wrong. It is just as probable that the program will fail silently and continue running until the damage done is very costly.
please help.
What do you want us to do? The only legal course of action is talking to the moderators of that forum on your behalf and convincing them to unban you. But we are random geeks, not mediators, so I cannot imagine why you are appealing to us instead of the people who banned you.
Now this will crash.
An example that actually compiles would help your case. ;)
I am not getting any errors, not even warnings(even if i use gcc -Wall test.c).
Empty structs are an extension in gcc. If you compile with switches that force standard compliance, you should at least get a warning:
gcc -Wall -ansi -pedantic test.c
But i've read about some which come only in VC++ and googling usually doesn't fix the issue :/
All compilers throw errors like that. That is why relying on google to solve your problems is not the best idea. ;) I have never gotten an error that I could not decipher after a some thinking, and I guess everyone else is the same, so switching compilers because you do not like the errors is a step backward. Now you have to learn what a whole new set of errors mean.
Anyway, VC++ is too big and Code::blocks is smaller
Now it seems like you are reaching for any reason to switch compilers. If you want to do it that badly, you do not need to justify the decision to me. But it is OK to backtrack if you ever find out that your original decision was not the best one. I have seen several projects die because the team could not stand to admit mistakes and kept chugging along on a path to doom.
I am not saying that your switching compilers is a path to doom, of course. Knowing more than one compiler is a good thing. But programmers thrive on logic, and a weak logical case like jumping from "throwing lots of stupid errors" to "X is to big and Y is smaller" is suspicious. ;)
Why can't we just use a pointer.
In C99 because a pointer might not work while an empty array will. Prior to C99, I cannot think of any reason why an array is better than a pointer except for keeping the array size out of the struct size when using sizeof
. I think the original struct hack uses an array size of 0, and it evolved to use 1 for compilers that do not allow an array size of 0.
So what is the problem?
What are instance variables please?
class Example
{
static int x; // static variable
int y; // instance variable
};
Instance variables are data members of a class where each object has a separate copy. They are distinct from static variables where every object of a class shares one copy.
Encapsulation is used to prevent users from viewing the inner workings of the interface.
I would say encapsulation is used primarily to prevent users from needing to know the inner workings to use objects of the class.
int array[4] = {1,2,3,4};
will work, but putting objects in headers is generally a bad idea because it is easy to accidentally define the object multiple times just by including the header more than once. Inclusion guards are only a partial fix for that problem.
Can you be specific about how the code you have tried does not work?
I get fed up of VC++ because i don't like the errors it throws
Why do you not like the errors it throws? If it is because the errors are always confusing and do not help you fix the problem, that is a legitimate reason to look for a different compiler. But I will warn you that from my experience, VC++ is no worse than other popular compilers out there. You just need to learn how to interpret the messages.
Just curious, what do you think C++ does when it passes by reference.
I think the easier implementation would pass by pointer and hide the pointer mechanics on the compiler side. A more "pure" implementation of references might somehow mark the reference and replace it with the same address as the original variable when generating machine code. That is neither here nor there as this is the C forum. :)
You said pass by reference doesn't copy the value or the address of the data.
Not so. I said something more general because C does not have native pass by reference semantics:
pass/call by reference uses the same object that was passed as an argument
How the same object is used is an implementation detail, and the detail does not matter as long as the effect of pass by reference is achieved without programmer intervention.
The programmer intervention part is why I do not believe C supports pass by reference. If I need to do something special beyond declaring a reference, the effect of pass by reference is not fully achieved. With pass by pointer I need to assign the address of the object before calling the function and I need to dereference the pointer to get to the object inside the function.
A struct with no members is not legal C. Your compiler should not allow it. C++ allows empty struct definitions, but all objects must have a size, so it will always be at least 1.
Is pass by value and call by reference the same?
No. Pass/Call by value makes an independent copy of the value for use in a function, but pass/call by reference uses the same object that was passed as an argument. Everyone likes to keep saying it, but C does not have pass by reference. It can only be faked passing pointers by value and using indirection them to get the original object.
why do we use call by value and pass by value? what are its uses?
Here is a 10,000 foot overview. Use pass by reference when:
Use pass by value when:
In the context of C, 'pass by reference' really means 'pass a pointer by value'. The whole thing is kind of a solved problem because C is such a small language. You either pass a pointer or not, depending on your needs. I think a more interesting question is whether or not value parameters should be made const:
void Function1(int x, int y);
void Function2(int const x, int const y);
But that is too far off topic for the thread. …
I think a bigger problem is that the recursive and iterative functions do not do anything remotely similar. If this program is supposed to be comparing two equivalent algorithms that solve the same problem, it is way off target. ;)
What are these functions supposed to be doing?
However, my integer to hex function gets stuck in an infinite loop and I have no clue why.
You never change the value of number inside the loop. The algorithm should be dividing it by 16 and storing the result, right? Also, 0 and '0' are two completely different values. Be sure to double check whether you are working in a string context or a numeric context and use the right constants.
n = number;
This will probably give you problems as well. The expression should be the other way around because number is the variable you are trying to initialize.
For the sake of not doing your homework, I will offer some advice only. The last character you will read on the line is '\n'. So if you read and ignore characters in a loop until '\n' is found, it will have the same effect as this call to ignore:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
but aren't RVA is on load time ? so code will be build but will crash ?
RVAs are converted to real addresses when the PE is loaded into memory by combining the PE base address with the RVA. The RVAs themselves are generated at build time for the executable. What happens depends on whether or not an overflow test is in place. If it is in place, the code will fail to build. If it is not in place, the code would probably build and load, but exhibit unpredictable behavior because the DWORD wrapped around and two variables have the same address. I have never heard of either problem happening, and that is why I think it is so rare as to be a non-issue.
If the array is the last one in the struct, you are probably seeing the struct hack. Prior to C99 it is an unportable trick for allocating arrays in a struct:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char s[1];
} String;
int main()
{
/* allocate 15 extra bytes for the string */
String *s = malloc(sizeof *s + 15);
strcpy(s->s, "test string");
puts(s->s);
free(s);
return 0;
}
The idea is that by tacking on extra memory and accessing it by overflowing the last array member, you can save an extra call to malloc:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *s;
} String;
int main()
{
String *s = malloc(sizeof *s);
s->s = malloc(15);
strcpy(s->s, "test string");
puts(s->s);
free(s->s);
free(s);
return 0;
}
C99 makes the struct hack a legal feature of the language, but I do not think it is a good idea even then because it makes the code less clear. ;)
then it would be like if-else if internally.
but here it is given as it uses jump tables
I think compilers commonly use jump tables for a tight range of cases and compares for wider ranges. This switch would probably use a jump table:
switch (condition)
{
case 0:
//...
break;
case 1:
//...
break;
case 2:
//...
break;
case 3:
//...
break;
case 4:
//...
break;
case 5:
//...
break;
}
But this switch would probably use compares and be close to the same result as the equivalent if statement because a jump table would be too big and too sparse:
switch (condition)
{
case 0:
//...
break;
case 10000:
//...
break;
case 5000:
//...
break;
case 40:
//...
break;
case 900:
//...
break;
case 123456:
//...
break;
}
I have heard about compilers using a jump table and binary search for switches that have a large number of cases and the range is wide.
then what is the advantage of using switch
If a switch is more intuitive then it makes the code clearer. Compilers are good at optimization, so you should not worry about which statement is more efficient and write code that is easy to read. The biggest performance changes come from whole algorithms anyway.
RVAs work like the segmented addresses. In the segmented memory model you have segments and offsets that combine to give the final address. An RVA is the offset that is combined to the PE's base address when loaded into memory.
what if there are many temperoralily variables wouldnt that overflow the that RVA value or i got the concenpt of RVA values all wrong ???
I do not know the answer, but if you use enough RVAs at the same time to fill up a DWORD without running out of some other critical resource first, I assume the code will not build. I do not think this is a risk that you should worry about.
1. Concept of Late binding can be acheived by Function pointers or indirect calls - This is due to the fact that compiler cannot simply substitute the address of the function when it encounters a function pointer, instead it needs to dereference it at a later stage.
That is my understanding too.
2. But in case of c++ compiler will associate a VPTR which points to a VTable while declaring a class when it encounters a virtual function.
Yes. The C++ compiler can generate and assign vtable addresses at compile time, but in C I did it manually for the vtable implementation and picking the vtable for new objects. The virtual method implementation was meant to show that even in C++ there is nothing special about methods. Internally they will probably be nothing more than regular functions with a special naming scheme that ties them to the class, like __Base_void_ToString_void
corresponding to void Base::ToString()
. If it is a virtual function, instead of using an inline definition, it just makes a call into the vtable using the index of the actual method definition.
My virtual method definition is the end result after an imaginary C++ compilation phase. Think of the original as this:
struct Base
{
int _x;
virtual void ToString()
{
//...
}
};
First the method is hoisted out of the struct and made a traditional function with the mangled name and taking this
as the first argument:
struct Base
{
int _x;
}; …
Anyone who has a good understanding of operating systems in addition to Windows, generally won't use Windows. Oh, they may repair it for other people, but they won't use it for themselves, except possibly for gaming.
Can you prove this without any weasel tricks like claiming that anyone who prefers Windows is ignorant? ;)
And no, it's not only hobbyists who "can afford to be extreme" about such things. Business owners like myself
So we're talking about business owners now and not IT professionals? My comment was about people who are forced to follow the rules of a client or employer, not people who make their own rules. If you have the option to choose your favorite tool, more power to you. Most of us are not so lucky.
So when you put things into their proper perspective, Unix, being the older operating system, should have a lot more problems.
Predictably, you missed the point and tried to twist it into a straw man for your Windows bashing. :)
Intolerant? Everything I've said has been accurate. If being right is intolerance, I hadn't heard that.
Yes, intolerant. You cannot be right about an opinion, because opinions are subjective. In your opinion Microsoft products are garbage, and you have a few bullet points that justify your opinion. Not respecting different opinions, like those of the people who prefer Windows, is intolerant.
Here is a simple example of one way to implement vtables in C:
#include <stdio.h>
/* class definitions */
typedef struct Base
{
void (**vtable)();
int _x;
} Base;
typedef struct Child
{
void (**vtable)();
/* begin base class slice */
int _x;
/* end base class slice */
int _y;
} Child;
/* class method implementations */
void Base_ToString(Base const* obj) { printf("Base: (%d)\n", obj->_x); }
void Child_ToString(Child const* obj) { printf("Base: (%d,%d)\n", obj->_x, obj->_y); }
/* vtable implementation */
enum { Call_ToString };
void (*Base_Vtable[])() = { &Base_ToString };
void (*Child_Vtable[])() = { &Child_ToString };
/* virtual method implementation */
void ToString(Base const* obj)
{
obj->vtable[Call_ToString](obj);
}
int main()
{
/* pick the vtable for objects at compile time */
Base base = {Base_Vtable, 123};
Child child = {Child_Vtable, 456, 789};
Base* a = &base;
Base* b = (Base*)&child;
/* call the virtual methods */
ToString(a);
ToString(b);
}
I did not include any code for handling multiple inheritance. That is harder to do. The implementation does not matter as long as the end result is the effect of late binding. Even vtables are not required, but it is a common implementation in C++ compilers.
Note: This example is not completely portable, but neither is a compiler. ;)
In my book book there is a similar kind of problem where it's mentioned that the input value should be less than 32767.
The range of signed int
is only assured to be at least[-32,767..+32,767]. If you want your code to be maximally portable, do not assume anything outside that range, or use signed long
instead, where the range is assured to be at least [-2,147,483,647..+2,147,483,647].
and the second thing is if i choose any number less than 32767, still i'm not geting the answer.
I get the right answer when I run this program, but the last printf() does not print a line break character, so my guess would be that this is your problem. If you do not print a line break, the output stream might not be flushed before the call to getch(), and you will not see the output. Replace that printf() call with this one and see if it fixes the problem:
printf("The desired value is:%d\n", total);
It really depends on how your compiler implements the pack
pragma, but usually it packs on the lesser of the value given or the natural boundary for the type. There is no address boundary less than char, so no matter what argument you give to pack
, it will use the natural boundary for char.
Well, real geeks don't run Windows. Real geeks don't run any Microsoft products, because we understand enough about operating systems and application programs, to know that Microsoft products are total, absolute, pieces of garbage.
I guess you can tweak your definition of 'geek' to mean what you want, but in my opinion a real geek would not limit his options by making generalizations. There are Microsoft products that are garbage, but there are also Microsoft products that are very good. The only company I know of that has been completely successful with every production so far is Pixar. ;)
Many of us 'geeks' are IT professionals, and banning Microsoft products would put us on the fast track to being out of work. Only hobbyists can afford to be extremist about these kind of things.
Even Microsoft admits that Windows was not designed to be secure.
Windows was also designed in the mid 1980s, when OS security was not exactly the buzzword that it is now. Couple that bad decision with the good decision of maintaining extensive backward compatibility and it is easy to see the dilemma of securing Windows without breaking functionality. I am not defending the insecurity, just putting things in perspective.
Maybe Windows 7 will be their successful attempt to hit that mark. I have not tried it yet, but soon my PC will be upgraded at work and I will also move to Windows 7.
I could continue - but you should have …
if first % 2 == 0;
Your syntax is close. Do not forget the parentheses, and lose the semicolon:
if (first % 2 == 0)
I have no idea for what I should use this (size_type) parameter.
If your allocator does not need it, do not worry about it. The allocator interface was designed to be generic, and some allocators will need that information to manage the memory. For example, moving blocks from a 'used' pool to a 'free' pool means knowing how many blocks to move. Or more simply, the size could be used for debug information.
The file is probably not open. Initialize first to something like 0 and see if the program prints that value instead of garbage. If it does, the file failed to open. This is a condition you can test easily without playing games with the variables:
ifstream in_stream("lab6file.txt");
if (!in_stream)
{
cerr << "file not open\n";
}
in_stream >> first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth;
Each variable should be separated by the extraction operator, not commas:
in_stream >> first >> second >> third >> fourth >> fifth
>> sixth >> seventh >> eighth >> ninth >> tenth;
in the first case: do I leave any garbage in the memory??
Yes. You return a reference to a Vector, then use the copy constructor to make a copy of it in v. It causes a memory leak because you lose the reference.
in the secound case: I have to call the destructor in order to not leave garbage in the memory. Right ?
The second case will probably crash because the pointer is uninitialized, but if you initialize the pointer, you still have the same problem of needing to save the address returned by the new operator so that you can delete it and not have a memory leak.
Your design of MakeVector is the root cause of these problems. It is confusing and dangerous. If you want to allocate dynamic memory, return a pointer instead of a reference. That way it is more obvious that the memory may need to be deleted and you do not need to use tricks to get the address:
Vector* MakeVector()
{
Vector* result = new Vector();
/* some more code */
return result;
}
Vector* v = MakeVector();
/* use v */
delete v;
What about portability?
It is very hard to write useful, fully featured software that has no unportable parts. Knowing when and how to sacrifice portability in a way that benefits the application the most is one of the more important skills, I think. Too bad it is also one of the most difficult.
Please post your code and the errors.
Its supposed to show the concept of recursion,
which is what the OP asked for.
Then we will have to disagree until the OP clarifies his question. I think he was asking for realistic uses of recursion, not contrived ones.
void CPU::setType(string newType); { type = newType; }
Above is an example of the problem. Look for the extra semicolon after the parameter list. That should not be there either. Rinse and repeat for all of your method definitions. And be careful when copy/pasting declarations and turning them into definitions. I accidentally copy the semicolon a lot too. ;)
In CPU.cpp, remove public
from all of the method definitions. C++ does not work like Java and C#, where the access level is applied to each entity.
I have problems understanding the code quickly whenever I need to go back to it after some time.
That is normal, and it is why code should be written as simply as possible without sacrificing functionality, and why comments that describe why you wrote something the way you did are critically important.
I started about a month ago , without planning much , and now I am struggling to understand the logic.
You should plan enough to understand how the application is supposed to work. The details can be ironed out during development, but the overall vision should not change much. Planning is even important for conversions because the target language might have better ways of designing the code. The result will probably be completely different from the original even though they both do the same thing. A straight line by line conversion of VB6 to C# is not a good idea, if you get my drift. ;)
Today I had a talk with a user and things cleared up much more .
I always make sure that clients are involved in the development process from start to finish, both to keep myself informed about their needs and to keep them informed about what I am doing. That way things do not get too far off track and everybody understands the vision of the final product.
I don't feel confident in my programming abilities because I can't predict when I'll finish a project .
Nobody can predict …
I'm sure there must be a better way to write it.
It looks OK to me. :) I only have one gripe, and it is a very small one:
for (int i = 1; i <= NR_ORDERS; i++)
The idiom for counted loops is an exclusive range of [0..N) instead of an inclusive range of [1..N] to avoid off-by-one errors.
it was what I did when I first learned about recursion
Yes, me too. Those examples are fine for learning how recursion works, but not for how it can be best used in real code. I think that is what the question was about, and that is why I replied the way I did.
I also wrote a function involving the fibonacci number sequence.
The best thing I learned from a recursive Fibonacci generator is how seemingly innocent code can be criminally inefficient. ;)
error C2660: 'CopyFileW' : function does not take 2 arguments
This is a different error. Read the documentation for CopyFile() and you will see that it takes 3 arguments, not 2.
The seed for each thread is independent. You need to call srand() in the Draw() function to reseed for each thread.
You tried it like this?
CopyFile(_T("\\svchost.exe","c:\\%windir%\\svchost.exe"), 0);
then what should be done in such situations???
Simple, don't get into those situations. :) If there is no predictable result for an expression, the best course of action is to avoid that expression. In your example you can break the expression down into multiple statements to make it do what you want, and you will make the code more clear at the same time.
A function to calculate factorials in math is a common example of recursion.
Linked list and binary tress use recursion
Here is a recursion that prints a message n number of time.
All of these are pretty bad examples of recursion because they can be written with iteration and there is no big loss of clarity or simplicity. Compare and contrast these implementations for examples 1 and 3:
#include <iostream>
#include <string>
long FactorialUsingRecursion(long n)
{
if (n < 2) return 1;
return n * FactorialUsingRecursion(n-1);
}
long FactorialUsingIteration(long n)
{
long x = 1;
while (n > 1) x *= n--;
return x;
}
void PrintUsingRecursion(std::string const& msg, int howMany)
{
if (howMany <= 0) return;
std::cout << msg << '\n';
PrintUsingRecursion(msg, howMany-1);
}
void PrintUsingIteration(std::string const& msg, int howMany)
{
while (--howMany >= 0) std::cout << msg << '\n';
}
int main()
{
std::cout << FactorialUsingRecursion(5) << '\n';
std::cout << FactorialUsingIteration(5) << '\n';
PrintUsingRecursion("recursion", 5);
PrintUsingIteration("iteration", 5);
}
Except for binary trees, they are also all linear problems and more prone to stack overflow. Good uses of recursion should have a benefit that outweighs the risk of stack overflow and the overhead of calling the same function over and over. I think quicksort is a better example because the recursive algorithm is much simpler than the iterative one, and with a good pivot finder stack overflow is not as much of a risk.
The biggest problem with giving examples is the best examples solve complex problems …
I know that it's a stretch, but I am looking for the third vulnerability in our practice program, and I can't find it.
It's a big stretch. Even with the minimum range of int and no safeguards by the runtime, there would have to be 32,768 command line arguments to overflow argc. Your practice program probably has a different third vulnerability. Is it possible to post the code?