|
Thread Rules 1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution. 2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20) 3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible. 4. Use [code] tags to format code blocks. |
On January 26 2013 09:30 Zeke50100 wrote: This isn't premature optimization at all.
Apart from the fact that this would be a tiny optimization that would likely make no difference in measurable speed whatsoever, you're still wrong about compilers not being able to optimize this.
Example code:
#include <iostream>
struct vec2 { int x,y; };
vec2 operator+(const vec2& a, const vec2&b) { vec2 result; result.x = a.x + b.x; result.y = a.y + b.y; return result; }
int main() { int x,y; vec2 a,b,c,d;
std::cin>>x; std::cin>>y; a.x = x; a.y = y; std::cin>>x; std::cin>>y; b.x = x; b.y = y; std::cin>>x; std::cin>>y; c.x = x; c.y = y; std::cin>>x; std::cin>>y; d.x = x; d.y = y;
a = a+b+c+d;
std::cout<<a.x<<" "<<a.y<<std::endl; return 0; }
compiled with the compiler in VS2005 (remember that compiler is 7+ years old) yields (for the relevant section)
00221328 mov ecx,dword ptr [esp+18h] 0022132C add ecx,dword ptr [esp+1Ch] 00221330 mov edx,dword ptr [esp+14h] 00221334 mov eax,dword ptr [esp+10h]
std::cout<<a.x<<" "<<a.y<<std::endl; 00221338 push dword ptr ds:[223044h] d.x = x; d.y = y;
a = a+b+c+d; 0022133E add edx,ebx 00221340 add ecx,edi 00221342 add edx,esi 00221344 add edx,dword ptr [esp+10h] 00221348 add eax,ecx
//right here there would be movs back to memory but the compiler doesn't do that and instead uses the registersto print to cout
Please show me how this can be rewritten to use less registers and/or addresses on the stack . Or point out the additional variable "somewhere in the middle". I'd be very surprised if GCC produces worse code than that.
Complete disassembly in spoilers:
+ Show Spoiler + int main() { 00221270 push ebp 00221271 mov ebp,esp 00221273 and esp,0FFFFFFF8h 00221276 sub esp,14h int x,y; vec2 a,b,c,d;
std::cin>>x; std::cin>>y; 00221279 mov ecx,dword ptr ds:[223058h] 0022127F push ebx 00221280 push esi 00221281 push edi 00221282 lea eax,[esp+0Ch] 00221286 push eax 00221287 call dword ptr ds:[22302Ch] 0022128D mov ecx,dword ptr ds:[223058h] 00221293 lea eax,[esp+10h] 00221297 push eax 00221298 call dword ptr ds:[22302Ch] a.x = x; a.y = y; 0022129E mov eax,dword ptr [esp+0Ch] std::cin>>x; std::cin>>y; 002212A2 mov ecx,dword ptr ds:[223058h] 002212A8 mov dword ptr [esp+14h],eax 002212AC mov eax,dword ptr [esp+10h] 002212B0 mov dword ptr [esp+1Ch],eax 002212B4 lea eax,[esp+0Ch] 002212B8 push eax 002212B9 call dword ptr ds:[22302Ch] 002212BF mov ecx,dword ptr ds:[223058h] 002212C5 lea eax,[esp+10h] 002212C9 push eax 002212CA call dword ptr ds:[22302Ch] b.x = x; b.y = y; 002212D0 mov eax,dword ptr [esp+10h] std::cin>>x; std::cin>>y; 002212D4 mov ecx,dword ptr ds:[223058h] 002212DA mov ebx,dword ptr [esp+0Ch] 002212DE mov dword ptr [esp+18h],eax 002212E2 lea eax,[esp+0Ch] 002212E6 push eax 002212E7 call dword ptr ds:[22302Ch] 002212ED mov ecx,dword ptr ds:[223058h] 002212F3 lea eax,[esp+10h] 002212F7 push eax 002212F8 call dword ptr ds:[22302Ch] c.x = x; c.y = y; std::cin>>x; std::cin>>y; 002212FE mov ecx,dword ptr ds:[223058h] 00221304 mov esi,dword ptr [esp+0Ch] 00221308 mov edi,dword ptr [esp+10h] 0022130C lea eax,[esp+0Ch] 00221310 push eax 00221311 call dword ptr ds:[22302Ch] 00221317 mov ecx,dword ptr ds:[223058h] 0022131D lea eax,[esp+10h] 00221321 push eax 00221322 call dword ptr ds:[22302Ch] d.x = x; d.y = y;
a = a+b+c+d; 00221328 mov ecx,dword ptr [esp+18h] 0022132C add ecx,dword ptr [esp+1Ch] 00221330 mov edx,dword ptr [esp+14h] 00221334 mov eax,dword ptr [esp+10h]
std::cout<<a.x<<" "<<a.y<<std::endl; 00221338 push dword ptr ds:[223044h] d.x = x; d.y = y;
a = a+b+c+d; 0022133E add edx,ebx 00221340 add ecx,edi 00221342 add edx,esi 00221344 add edx,dword ptr [esp+10h] 00221348 add eax,ecx
std::cout<<a.x<<" "<<a.y<<std::endl; 0022134A mov ecx,dword ptr ds:[22305Ch] 00221350 push eax 00221351 push edx 00221352 call dword ptr ds:[223034h] 00221358 mov ecx,eax 0022135A call std::operator<<<std::char_traits<char> > (0221810h) 0022135F mov ecx,eax 00221361 call dword ptr ds:[223034h] 00221367 mov ecx,eax 00221369 call dword ptr ds:[223038h] return 0; } 0022136F pop edi 00221370 pop esi 00221371 xor eax,eax 00221373 pop ebx 00221374 mov esp,ebp 00221376 pop ebp 00221377 ret
|
Do you really want to suffer the drawback of creating tons of temporary objects just to make it look prettier? Ask yourself few months into the development.
Stack allocation of temporary objects is like, an addition to the stack pointer, followed by assignment into those stack addresses, which are almost always in the cache. Or into the registers.
With far away re-used variables, additional pointer parameters, heap allocation, or other tricks to get around temporary objects, you are only making things worse. Both performance and clarity wise.
If you are really that worried about temporary objects, use the move semantics found in C++11. It solves most of the worries about temporary objects.
What about more complicated objects, when you're suddenly tossing around the stack like a ragdoll due to the sheer size of every object? Consider moving out said complicated objects to the heap, it has like 100 times as much capacity, and is more friendly to polymorphic objects.
if anything, having both the helper function and the operator would be preferred Only keep one, you are only making the maintenance harder.
Few advices that come to my mind: - Do not use comments, especially not as compensation for illegible code. They are only noise in the code, they are always outdated, hard to read, or outright lying. - Code cleanly, with the most appropriate tools and constructs you have, don't hack your way around perceived problems, don't reinvent the wheel. Chances are, it is already solved on some level; compiler optimization, language extension, library, etc. - These tools include the features provided by the language. They are there for a reason, use them when they are appropriate. - Don't reuse variables, it's like the most uglies way to mess up your code. - Think about the lifetime of objects and allocate them on the stack or on the heap accordingly. - Don't optimize prematurely. Worry about performance only when you actually have a well-tested, end-to-end working software and you can actually measure its bottlenecks. You can be surprised about the lack of obvious bottlenecks. - Read Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. This is the book that introduced me to clean code, TDD, refactoring and code quality, and it does a very good job at explaining why is it important. - Code in Java for a few months with Eclipse. Your perspective and your C++ skills will improve.
|
On January 26 2013 10:07 Frigo wrote:Show nested quote +Do you really want to suffer the drawback of creating tons of temporary objects just to make it look prettier? Ask yourself few months into the development. Stack allocation of temporary objects is like, an addition to the stack pointer, followed by assignment into those stack addresses, which are almost always in the cache. Or into the registers. With far away re-used variables, additional pointer parameters, heap allocation, or other tricks to get around temporary objects, you are only making things worse. Both performance and clarity wise. If you are really that worried about temporary objects, use the move semantics found in C++11. It solves most of the worries about temporary objects. Show nested quote +What about more complicated objects, when you're suddenly tossing around the stack like a ragdoll due to the sheer size of every object? Consider moving out said complicated objects to the heap, it has like 100 times as much capacity, and is more friendly to polymorphic objects. Show nested quote +if anything, having both the helper function and the operator would be preferred Only keep one, you are only making the maintenance harder. Few advices that come to my mind: - Do not use comments, especially not as compensation for illegible code. They are only noise in the code, they are always outdated, hard to read, or outright lying. - Code cleanly, with the most appropriate tools and constructs you have, don't hack your way around perceived problems, don't reinvent the wheel. Chances are, it is already solved on some level; compiler optimization, language extension, library, etc. - These tools include the features provided by the language. They are there for a reason, use them when they are appropriate. - Don't reuse variables, it's like the most uglies way to mess up your code. - Think about the lifetime of objects and allocate them on the stack or on the heap accordingly. - Don't optimize prematurely. Worry about performance only when you actually have a well-tested, end-to-end working software and you can actually measure its bottlenecks. You can be surprised about the lack of obvious bottlenecks. - Read Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. This is the book that introduced me to clean code, TDD, refactoring and code quality, and it does a very good job at explaining why is it important. - Code in Java for a few months with Eclipse. Your perspective and your C++ skills will improve. To the general discussion I want to agree with the guys saying that, even if there was slight efficiency loss, the readability gain for a long term project is worth it. But regarding your points, could you elaborate on the last one ?
|
On January 26 2013 10:20 mcc wrote: To the general discussion I want to agree with the guys saying that, even if there was slight efficiency loss, the readability gain for a long term project is worth it. But regarding your points, could you elaborate on the last one ? Well, C++ lacks a lot of comfort features, leaves a lot of behavior undefined, keeps unneeded C compatibility features, and for any given thing, there is at least 3 ways to do it, all with their own set of problems and annoying details. This makes casual coding in it pretty difficult.
In Java on the other hand, the language has more integrity and is more modern, standard libraries cover more territory, library support is better, IDEs are easier to use, etc. You need less effort to start coding in it and can focus more on the design and structure of your program, rather than trying to understand and struggle with peculiar aspects of the language. You focus more on programming itself and keep improving the software engineer in you.
Then when (if) you return to C++, you will have a true high-level perspective on C++, instead of a low-level, C perspective. Suddenly the language features and the flexibility start to make sense. You will no longer try to prematurely optimize performance or memory consumption, you will no longer see C++ as C-with-class-instead-of-struct-keyword, you will learn to use and value the language features, use classes and methods over primitives and functions, use stack and heap where appropriate, use pass by value, pass by pointer and pass by reference where appropriate. You will no longer write screens of unstructured code, you will use methods and objects as intended. You will get yourself rid of the annoying habits and hacks of C and bad C++.
You will be able to focus on programming itself instead of the peculiarities of the language.
|
On January 26 2013 09:48 heishe wrote:Show nested quote +On January 26 2013 09:30 Zeke50100 wrote: This isn't premature optimization at all. Apart from the fact that this would be a tiny optimization that would likely make no difference in measurable speed whatsoever, you're still wrong about compilers not being able to optimize this.
My main concern was with the creation of temporary variables and not how many instructions would exist in the assembly.
+ Show Spoiler [Example Code] +#include <iostream>
class vec2 { public: int x, y; vec2(int _x, int _y) : x(_x), y(_y) { std::cout << "Constructing vector at " << this << " with values " << x << " " << y << "\n"; }
//Is never called vec2(const vec2& copy) { std::cout << "Copy constructing vector at " << © << " with values " << copy.x << " " << copy.y << "\n"; }
vec2 operator+(const vec2& rhs) const { return vec2(x + rhs.x, y + rhs.y); } };
void vec2Add(vec2* dest, const vec2* src1, const vec2* src2) { dest->x = src1->x + src2->x; dest->y = src1->y + src2->y; }
int main() { vec2 a(0, 0), b(1, 1), c(2, 2), d(3, 3); //4 constructors called
vec2Add(&a, &a, &b); //a = a + b vec2Add(&a, &a, &c); //a = a + c // a = a + b + c vec2Add(&a, &a, &d); //a = a + d // a = a + b + c + d
std::cout << "Using vec2Add, a has values: " << a.x << " " << a.y << "\n\n";
vec2 v1(0, 0), v2(1, 1), v3(2, 2), v4(3, 3); //4 constructors called v1 = v1 + v2 + v3 + v4;
std::cout << "Using operator+, v1 has values: " << v1.x << " " << v1.y << "\n\n";
std::cin.get(); return 0; }
This is just a quick example to show the number of times the objects are constructed. Both parts initially create 4 vec2 objects, then perform "a = a + b + c + d" (or, in the second case, "v1 = v1 + v2 + v3 + v4"); both methods have the exact same result. What actually goes on underneath is a bit different, though:
Constructing vector at 002AFD60 with values 0 0 Constructing vector at 002AFD70 with values 1 1 Constructing vector at 002AFD78 with values 2 2 Constructing vector at 002AFD80 with values 3 3 Using vec2Add, a has values: 6 6
Constructing vector at 002AFD68 with values 0 0 Constructing vector at 002AFD88 with values 1 1 Constructing vector at 002AFD90 with values 2 2 Constructing vector at 002AFDA0 with values 3 3 Constructing vector at 002AFD98 with values 1 1 Constructing vector at 002AFDA8 with values 3 3 Constructing vector at 002AFDB0 with values 6 6 Using operator+, v1 has values: 6 6
The second method ended up with 3 additional constructions of vec2 objects. It's not exactly a fair comparison, so I quickly changed it around not to construct v1 until it's assigned a value, which reduced the number of additional constructions to 1. Still, there's at least 1 temporary variable associated with vector addition that is unnecessary.
|
On January 26 2013 11:02 Frigo wrote:Show nested quote +On January 26 2013 10:20 mcc wrote: To the general discussion I want to agree with the guys saying that, even if there was slight efficiency loss, the readability gain for a long term project is worth it. But regarding your points, could you elaborate on the last one ? Well, C++ lacks a lot of comfort features, leaves a lot of behavior undefined, keeps unneeded C compatibility features, and for any given thing, there is at least 3 ways to do it, all with their own set of problems and annoying details. This makes casual coding in it pretty difficult. In Java on the other hand, the language has more integrity and is more modern, standard libraries cover more territory, library support is better, IDEs are easier to use, etc. You need less effort to start coding in it and can focus more on the design and structure of your program, rather than trying to understand and struggle with peculiar aspects of the language. You focus more on programming itself and keep improving the software engineer in you. Then when (if) you return to C++, you will have a true high-level perspective on C++, instead of a low-level, C perspective. Suddenly the language features and the flexibility start to make sense. You will no longer try to prematurely optimize performance or memory consumption, you will no longer see C++ as C-with-class-instead-of-struct-keyword, you will learn to use and value the language features, use classes and methods over primitives and functions, use stack and heap where appropriate, use pass by value, pass by pointer and pass by reference where appropriate. You will no longer write screens of unstructured code, you will use methods and objects as intended. You will get yourself rid of the annoying habits and hacks of C and bad C++. You will be able to focus on programming itself instead of the peculiarities of the language. I see what you mean. That is one way to do it. Another I think is to work on big, well-led C++ project that forces you to do the same. In general I think working on reasonably big projects (as in 10/15+ developers) for long period of time so you will also taste bugfixing issues is pretty good school how to develop good programming habits. Especially the bugfixing part teaches you a lot - ah the hours spent over stacks corrupted due to uninitialized pointers At least in my case that thought me a lot of valuable lessons on the high-level engineering side of things. And I think even if you work with Java/C# you need the experience from really big team projects to develop some of the necessary habits.
|
On January 26 2013 11:19 Zeke50100 wrote: Still, there's at least 1 temporary variable associated with vector addition that is unnecessary. Use += duh. No temporary objects whatsoever.
I don't understand what more do you expect. The compiler won't magically know the commutative and other properties of your addition operator to optimize away the construction of the actual result, especially after you explicitly refer to the constructor in the operator. It is smart enough however, to store them in registers, or in the cache so temporary objects become a non-issue.
|
On January 26 2013 11:19 Zeke50100 wrote:Show nested quote +On January 26 2013 09:48 heishe wrote:On January 26 2013 09:30 Zeke50100 wrote: This isn't premature optimization at all. Apart from the fact that this would be a tiny optimization that would likely make no difference in measurable speed whatsoever, you're still wrong about compilers not being able to optimize this. My main concern was with the creation of temporary variables and not how many instructions would exist in the assembly. + Show Spoiler [Example Code] +#include <iostream>
class vec2 { public: int x, y; vec2(int _x, int _y) : x(_x), y(_y) { std::cout << "Constructing vector at " << this << " with values " << x << " " << y << "\n"; }
//Is never called vec2(const vec2& copy) { std::cout << "Copy constructing vector at " << © << " with values " << copy.x << " " << copy.y << "\n"; }
vec2 operator+(const vec2& rhs) const { return vec2(x + rhs.x, y + rhs.y); } };
void vec2Add(vec2* dest, const vec2* src1, const vec2* src2) { dest->x = src1->x + src2->x; dest->y = src1->y + src2->y; }
int main() { vec2 a(0, 0), b(1, 1), c(2, 2), d(3, 3); //4 constructors called
vec2Add(&a, &a, &b); //a = a + b vec2Add(&a, &a, &c); //a = a + c // a = a + b + c vec2Add(&a, &a, &d); //a = a + d // a = a + b + c + d
std::cout << "Using vec2Add, a has values: " << a.x << " " << a.y << "\n\n";
vec2 v1(0, 0), v2(1, 1), v3(2, 2), v4(3, 3); //4 constructors called v1 = v1 + v2 + v3 + v4;
std::cout << "Using operator+, v1 has values: " << v1.x << " " << v1.y << "\n\n";
std::cin.get(); return 0; } This is just a quick example to show the number of times the objects are constructed. Both parts initially create 4 vec2 objects, then perform "a = a + b + c + d" (or, in the second case, "v1 = v1 + v2 + v3 + v4"); both methods have the exact same result. What actually goes on underneath is a bit different, though: Constructing vector at 002AFD60 with values 0 0 Constructing vector at 002AFD70 with values 1 1 Constructing vector at 002AFD78 with values 2 2 Constructing vector at 002AFD80 with values 3 3 Using vec2Add, a has values: 6 6 Constructing vector at 002AFD68 with values 0 0 Constructing vector at 002AFD88 with values 1 1 Constructing vector at 002AFD90 with values 2 2 Constructing vector at 002AFDA0 with values 3 3 Constructing vector at 002AFD98 with values 1 1 Constructing vector at 002AFDA8 with values 3 3 Constructing vector at 002AFDB0 with values 6 6 Using operator+, v1 has values: 6 6 The second method ended up with 3 additional constructions of vec2 objects. It's not exactly a fair comparison, so I quickly changed it around not to construct v1 until it's assigned a value, which reduced the number of additional constructions to 1. Still, there's at least 1 temporary variable associated with vector addition that is unnecessary.
Beside the fact that the number+type of assembly instructions (and the most optimal order of them being executed) should be the ONLY thing you strive for with non-algorithmic optimization like this (since nothing else makes your program faster), you're completely missing something yet again:
Of course if you print something in the constructor, the compiler won't be able to optimize it away. If you don't have those outputs in the constructor, there will not be any additional unnecessary objects constructed.
If you wanted to make a point that an unoptimized version of the code produces more temporary copies then yeah, you're right, but you're contradicting yourself since you said yourself that this is about opimization, by saying "this is not premature optimization at all"
Please, for the sake of your invested time and anyone who's working with your "optimized code", just don't do it. Take it from someone who has a lot more experience in high-performance optimization in a professional environment than you.
|
Let me say this again because I did not stress it enough:
First have a working, well-tested version of your software. Then you can start thinking about which parts should you optimize, if you are unsatisfied with its performance.
Not the other way around.
|
Hello,
Hope you guys don't mind a noobie question. I'm pretty new to programming still and am having a problem with a visual basic program that is supposed to take 5 inputted values in the same textbox(1 value at a time, clearing after each entry) and then display them as they're entered in another multiline texbox below and store them in an array. Next, a loop is to be used on the array to calculate the average of the inputted numbers.
My problem thus far is trying to get the 5 values stored in the array, and both my textbook and google have failed me.
What little I have so far... + Show Spoiler + 'Input inputScore = txtScores.Text If Not IsNumeric(txtScores.Text) Then MsgBox("Score must be between 1 and 300") ElseIf txtScores.Text.Contains(".") Then MsgBox("Score must be a whole number") ElseIf txtScores.Text < 1 Or txtScores.Text > 300 Then MsgBox("Score must be between 1 and 300") Else : txtAllScores.Text = txtAllScores.Text & vbCrLf & inputScore End If ' ??? allScores(4) = txtAllScores.Text
|
Is that your button click event?
Your first error message is wrong, btw. Secondly, if you're going to store your .Text value in a variable, you should use that variable for your error checking instead of going back to the .Text property each time.
Assuming your array is declared with a length of 5, all you need to do is just add the current value to the next slot each time. The simplest method is just to have a class-level integer that you increment each time and use to track which position you're at.
I don't remember offhand if integer arrays have a way to "know" how many values are actually present. The length / count fields just tell you the number of elements (which is 5, since that's how it's declared). You alternatively could just iterate your array with each button click to find which index to use. You could also ReDim each time, but I don't recommend that approach.
List(Of Integer) is much nicer for this kind of thing -- you could simply do a .Add(someval) each time. I'm assuming that this awkwardly forced approach is because of the assignment.
Additionally, you could iterate the multiline listbox during calculate to fill your array and avoid this issue.
I'd do something simple like:
Imports System.Collections.Generic Public Class Form1 Dim scoreList As List(Of Integer) = New List(Of Integer)
Private Sub btnAddScore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddScore.Click ' <Input Validation Here> scoreList.Add(Convert.ToInt32(txtOneScore.Text)) txtAllScores.Text += Environment.NewLine & txtOneScore.Text End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click For Each i As Int32 In scoreList ' Do something Next End Sub End Class
|
I'm doing a home exercise about C programming and im kinda stuck on the first question about memory allocation and I'd be glad if someone could try to explain this to me.
Code:+ Show Spoiler +10 #include <malloc.h> 11 #include <stdio.h> 12 #include <stdlib.h> 13 14 int gi; /* Global variable. */ 15 int in = 4711; /* Global variable, initialized to 4711. */ 16 17 int fun( int parm ) 18 { 19 /* Local variable, initialized every time fun is called. */ 20 int loc1 = parm + 17; 21 22 printf( "AF.1: loc1 stored at %lx (hex); value is %d (dec), %x (hex)\n", 23 (long) &loc1, loc1, loc1 ); 24 printf( "AF.2: parm stored at %lx (hex); value is %d (dec), %x (hex)\n", 25 (long) &parm, parm, parm ); 26 27 gi = parm; /* Change the value of a global variable. */ 28 printf( "AF.3: Executed gi = parm;\n" ); 29 return( loc1 ); 30 } 31 32 /* Main function. */ 33 int main() 34 { 35 /* Local variables. */ 36 int m; 37 int n; 38 int * p; /* Declare p as pointer, so that p can hold an address. */ 39 /* Do some calculation. */ 40 gi = 12345; 41 m = gi + 11111; 42 n = 17; 43printf( "Message AM.01 from areas.c: Hello, World!\n" ); 45 46 printf( "AM.02: m: stored at %lx (hex); value is %d (dec), %x (hex)\n", 47 (long) &m, m, m ); 48 printf( "AM.03: n: stored at %lx (hex); value is %d (dec), %x (hex)\n", 49 (long) &n, n, n ); 50 printf( "AM.04: gi: stored at %lx (hex); value is %d (dec), %x (hex)\n", 51 (long) &gi, gi, gi ); 52 printf( "AM.05: in: stored at %lx (hex); value is %d (dec), %x (hex)\n", 53 (long) &in, in, in ); 54 55 printf( "AM.06: fun: address is %lx (hex)\n", (long) fun ); 56 printf( "AM.07: main: address is %lx (hex)\n", (long) main ); 57 58 p = (int *) malloc( sizeof( int ) ); 59 printf( "AM.08: Executed p = (int *) malloc( sizeof( int ) );\n" ); 60 printf( "AM.09: p: stored at %lx (hex); value is %ld (dec), %lx (hex)\n", 61 (long) &p, (long) p, (long) p ); 62 63 printf( "AM.10: Will soon execute n = fun( m );\n" ); 64 n = fun( m ); 65 printf( "AM.11: Has now returned from n = fun( m );\n" ); 66 67 printf( "AM.12: n: stored at %lx (hex); value is %d (dec), %x (hex)\n", 68 (long) &n, n, n ); 69 printf( "AM.13: gi: stored at %lx (hex); value is %d (dec), %x (hex)\n", 70 (long) &gi, gi, gi ); 71 72 free( p ); 73 exit( 0 ); 74 }
Now the exercise wants me to list in what memory area is the variables gi,in,m,p and what memory area does the pointer p point to, and the answer to these questions i can choose between code, data, bss, stack or heap
now what i've figured out is that all variables declared in the main function is put on the stack and the pointer itself is put on the stack. But i cant figure what decides if the variable is either put on data, bss or heap
|
For future reference, when posting code, please use proper indentation so we can read it more easily.
int main() { int foo = 1; return foo; } // This is good
int main() { int foo = 1; return foo; } // This is bad
To answer your question, you simply need to find a decent definition of the different memory segments, and then look at where each variable is being declared and assigned. Here's a good start: http://en.wikipedia.org/wiki/Data_segment
Definitions are roughly,
global/static/etc - data global/static/etc uninitialized - bss function local variables - stack blocks of data controlled by malloc - heap
---
the actual bits that represent instructions in your code (think assembly) - code
An important point in computer security is that without proper care, you can accidentally (or purposefully) write stuff into the wrong section. Buffer overflow is fun
|
Was playing around if the indent tag works in the code brackets and accidently pressed post instead of preview. oops
|
bss is for zero-initialized stuff which includes uninitialized global and static variables (which are initialized to 0 by default) or the same types which are explicitly (redundantly) initialized to 0.
|
EDIT: JAVA
Hi all, I just found this thread not too long ago and am having trouble starting this project. The project is as follows:
+ Show Spoiler +Write a grading program for a class with the following grading policies: a. There are three quizzes, each graded on the basis of 10 points. b. There is one midterm exam, graded on the basis of 100 points. c. There is one final exam, graded on the basis of 100 points. The final exam counts for 40% of the grade. The midterm counts for 35% of the grade. The three quizzes together count for a total of 25% of the grade. (Do not forget to convert the quiz scores to percentages before they are averaged in.) Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but less than 70) is a D, and any grade below 60 is an F. The program should read in the student’s scores and output the student’s record, which consists of three quiz scores and two exam scores, as well as the student’s overall numeric score for the entire course and final letter grade. Define and use a class for the student record. The class should have instance variables for the quizzes, midterm, final, overall numeric score for the course, and final letter grade. The overall numeric score is a number in the range 0 to 100, which represents the weighted average of the student’s work. The class should have methods to compute the overall numeric grade and the final letter grade. These last methods should be void methods that set the appropriate instance variables. Your class should have a reasonable set of accessor and mutator methods, an equals method, and a toString method, whether or not your program uses them. You may add other methods if you wish.
Additional information: Use two classes to do this assignment. Name the first class TestGrade, it will be a driver class that is to create an instance of the second class, prompt and get values, and display values. The second class will be named Grade, this is where all the core logic in contained.
I always seem to have trouble getting the ball rolling, but once I do I can generally figure out where to head from there. Any tips on getting this set up would be greatly appreciated! Feel free to PM as well.
Thanks!
|
On January 28 2013 12:33 Mistakes wrote:EDIT: JAVA Hi all, I just found this thread not too long ago and am having trouble starting this project. The project is as follows: + Show Spoiler +Write a grading program for a class with the following grading policies: a. There are three quizzes, each graded on the basis of 10 points. b. There is one midterm exam, graded on the basis of 100 points. c. There is one final exam, graded on the basis of 100 points. The final exam counts for 40% of the grade. The midterm counts for 35% of the grade. The three quizzes together count for a total of 25% of the grade. (Do not forget to convert the quiz scores to percentages before they are averaged in.) Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but less than 70) is a D, and any grade below 60 is an F. The program should read in the student’s scores and output the student’s record, which consists of three quiz scores and two exam scores, as well as the student’s overall numeric score for the entire course and final letter grade. Define and use a class for the student record. The class should have instance variables for the quizzes, midterm, final, overall numeric score for the course, and final letter grade. The overall numeric score is a number in the range 0 to 100, which represents the weighted average of the student’s work. The class should have methods to compute the overall numeric grade and the final letter grade. These last methods should be void methods that set the appropriate instance variables. Your class should have a reasonable set of accessor and mutator methods, an equals method, and a toString method, whether or not your program uses them. You may add other methods if you wish. Additional information: Use two classes to do this assignment. Name the first class TestGrade, it will be a driver class that is to create an instance of the second class, prompt and get values, and display values. The second class will be named Grade, this is where all the core logic in contained. I always seem to have trouble getting the ball rolling, but once I do I can generally figure out where to head from there. Any tips on getting this set up would be greatly appreciated! Feel free to PM as well. Thanks!
"How do I start" is a bit general. What specifically do you not understand about the project? If you want to know what to do first, I would write the code to get the scores from the user (are the scores in a text file? user input? other? I assume you know this). After that the assignment is pretty clear what you have to do with that information.
|
Hey guys this thread seems very very informative. I seem to have gotten late to the party, wow 233 pages! Anyways im kinda having a bit of an issue. You see, i was a civil engineering major, however as of lately ive really lost interest in it. I've found that as i learn more and more about what the daily job of a civil engineer is, it interests me less and less. This kinda sucks because it was really all i had thought about studying, however im pretty much about 90% sure that im going to switch my major now rather than finish it only to be bored of it! Seeing as how i like computers so much, and i love visiting the xda-dev website to read up on topics and it always amazes me how the devs there accomplish things, i've thought that maybe software engineering would be a good major to switch to. I think it might offer me that space to be creative and i could put the skills learned to making my own programs in my spare time and who knows maybe even an app or something.
I've also read that job prospects are very good and you can be employed in a great variety of places. The major i was eyeing is Computer Science, with a software development track (as is stated by my university). Switching to this major would allow me to make use of the math that i've learned thus far and i wouldn't have to start from zero because of the overlapping classes up to a certain point. However, i have never EVER done any programming whatsoever and honestly don't even know where to start. So here's my question to you guys. I have four months of free time until my semester at the uni starts and i want to put it to good use. I want to dip my feet into programming so when i start Uni i wont be completely clueless. I THINK the first programming course at the Uni is Java. That being said, what should i devote these next four months to? I obviously read the op but its still not clear to me which language i should devote to first? Should i start with java since i'll be learning java first course anyways? Or should i do c++? IDK! please give me some advice!
|
Anyone got any good tips for C# books, as I'm thinking if familiarizing myself with that language later in the spring.
On January 28 2013 14:30 HeavenS wrote: I have four months of free time until my semester at the uni starts and i want to put it to good use. I want to dip my feet into programming so when i start Uni i wont be completely clueless. I THINK the first programming course at the Uni is Java. That being said, what should i devote these next four months to? I obviously read the op but its still not clear to me which language i should devote to first? Should i start with java since i'll be learning java first course anyways? Or should i do c++? IDK! please give me some advice! If you are going to learn Java first, then I'd recommend that you familiarize yourself with it. Java is IMO not an overomplecated language for beginner. Plus it has (compared to C++) a big standard library, so that you won't feel that you have to reinvent the wheel several times over.
But if you are going to learn C++ later on (which is the way I interpret it), I have to say that learning about dynamic memory allocation and C++-pointers might be confusing at first.
|
|
|
|
|