Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
shrughes
Oct 11, 2008

(call/cc call/cc)

Zakath posted:

You're right, it was just what led me to this, and has no bearing on my question.

Is there any way of checking for this kind of undesired assignment?

Use a Microsoft compiler.

Adbot
ADBOT LOVES YOU

Princess Kakorin
Nov 4, 2010

A real Japanese Princess
I need a refresher.
The size of a pointer or reference is small, as it only represents the memory address of whatever it's pointing/referring to right?
For example; say I have some object A that takes up 25MB of space on the stack.

code:
A* pointsToObjA = new A;

A* would only take up what little space a memory address takes up while new A would take up the 25MB.

Then, this variable myPointerToA would also take up whatever small space a memory address takes up too, correct?
code:
class A {...};

class B
{
  public:
   B(A* pointerToA) 
    { myPointerToA = pointerToA; }
  private:
    A* myPointerToA;

};

EDIT: And what's the deal with void pointers? I've read up on them, but don't quite grasp them.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!

Princess Kakorin posted:

EDIT: And what's the deal with void pointers? I've read up on them, but don't quite grasp them.
Void pointers are for representing a pointer that could be to anything rather than data of any particular type. The stride of the contents is unknown so pointer arithmetic and indexes on them are illegal, the only thing you can do with them is cast them to a more useful type.

A nice example of where this is useful is memcpy, which takes a void pointer destination and a constant void pointer source, and the reason for that is that memcpy is a legal function to call on any type of data, whether it's a number, a structure, or array of values.


"new" is an allocation operation, it allocates a block of memory and returns a pointer to it, so the result of "new A" is actually a pointer of the type "A*"

w00tz0r
Aug 10, 2006

I'm just so god damn happy.

Princess Kakorin posted:

The size of a pointer or reference is small, as it only represents the memory address of whatever it's pointing/referring to right?
...
Then, this variable myPointerToA would also take up whatever small space a memory address takes up too, correct?

Right on both counts. The size of B::myPointerToA will be whatever the pointer size is on your system, not the full 25 megabytes of an A.

Princess Kakorin posted:

EDIT: And what's the deal with void pointers? I've read up on them, but don't quite grasp them.

Someone else can probably give a better explanation, but basically it's just a pointer to a block of memory without any context of what's stored there. You'll generally see it in C functions that take a generic argument (ie: qsort()), or if you're implementing some sort of opaque type where you don't want the user to know or care about implementation details.

The first example of an opaque type that comes to mind is the Windows HANDLE typedef, which is just a void*. The functions that return them don't want you modifying their underlying implementation at all, so they return a type that has no context information at all. It's up to functions that accept a HANDLE to cast it to the type that they expect - if you pass it the wrong type, it'll compile, but fail at runtime since the cast produced the wrong result.

The C qsort() function is similar, in that the predicate function you supply has to accept two void pointers, and the function is responsible for casting them to the correct type - in this case you're not hiding the implementation, but it allows the library code to not care about it.

w00tz0r fucked around with this message at 07:49 on Feb 29, 2012

Computer viking
May 30, 2011
Now with less breakage.

Cyril Sneer posted:

Can you elaborate on this a bit?

Certainly.
If you grab the free edition of KomodoEdit and install it, you can open remote files like this:


File->Open remote, gets you to ...

this - where you have to set up your server info the first time. To do that, click the appropriate button, and you get this:

Fill it out with the same info you'd use to ssh in. If you don't know the appropriate default path, leave it empty - it should work out anyway. If sftp doesn't work, try scp. Save, and in the open dialog pick the server you just set up - you're now browsing the remote end.

Pick the relevant file, and you can edit it. ( I think what technically happens is that it grabs a local temporary copy and opens that, and saving uploads it back on top of the original.)

Like so. Ignore my personal-use-only quality C. (Looking at that - WhyTH am I using an uint64_t instead of an int? None of those quantities would ever overflow a signed 32-bit int, and file descriptors are standardized as "int" specifically. Oh well, it does work, and I do other things further in that genuinely requires ints larger than 32 bits. And I love the error handling in the no-arguments case - segfaults count as informative error messages, right?)

Computer viking fucked around with this message at 16:53 on Feb 29, 2012

Volte
Oct 4, 2004

woosh woosh
Strangely the best free way to transparently edit remote files on Windows I've found is using Notepad++ with the bundled NppFtp plugin, which supports SFTP. I'm not a huge fan of Notepad++ in general but that particular feature is really nice, and Notepad++ is pretty lightweight.

Computer viking
May 30, 2011
Now with less breakage.

Volte posted:

Strangely the best free way to transparently edit remote files on Windows I've found is using Notepad++ with the bundled NppFtp plugin, which supports SFTP. I'm not a huge fan of Notepad++ in general but that particular feature is really nice, and Notepad++ is pretty lightweight.

Heh, I use notepad++ now and then, and I hadn't noticed that. Useful.

Helg56
Feb 16, 2012

by Y Kant Ozma Post
I am new to this forum, this is actually my first post, I read a lot but never say anything. But to get to my post. I am making a web server in C and just having a hell of a time getting even simple pages like Google.com to load into my browser. I have it able to load in the basic html of the Google.html I downloaded but it wont load the pictures for some reason.

here is the area of my code that gets and sends the file to the browser.
code:
else{
        if( ptr[strlen(ptr) - 1] == '/' ){
           printf("ptr1 == %c\n", *ptr);
	   strcat(ptr,"Google.html");
	}
	printf("ptr2 == %c\n", *ptr);
	strcpy(resource, webroot);
	strcat(resource, ptr);
	file = fopen("./Google.html","r+");
	if(file == NULL){
	    printf("404 File not found error\n");
	    rdysend(nsock,"HTTP/1.0 404 Not Found\r\n");
	    fclose(file);
	}
	//while(length >=0){
	else{
		printf("200 OK\n");
		rdysend(nsock,"HTTP/1.0 200 OK\r\n");
		rdysend(nsock,"Server : Localhost:\r\n\r\n");
		if( ptr == request+4 ) // if it is a get request
		{
		   fseek(file, 0, SEEK_END);
		   length = ftell(file);
		   rewind(file);
		   if(length != 0 )
		      printf("Error getting size \n");
		   if( (ptr = (char *)malloc(length) ) == NULL )
		      printf("Error allocating memory!!\n");
		   fread(ptr, 1, length, file);
 
		   if(send(nsock,ptr,length,0) == -1){
			printf("Send err!!\n");
		}
		free(ptr);
	}
}
close(nsock);
}
I can supply more code if needed, I didn't want to make a wall of text for everyone.

I have my Google.html and the file with all of the images for the Google.html in the same directory as my executable.

Any help is much appreciated! :)

Computer viking
May 30, 2011
Now with less breakage.

Uhm.
a) Why are you testing with google's html? Write yourself a test page, it'll take all of 20 seconds and be much easier to test with than the spectacularly unreadable google front page.
b) Won't all the img tags on there refer to specific, different, servers? If you want to dump the images in the same folder as the html file, they have to be on the form <img src="file.png" />, without any domain names. As far as I can see, that's not the case on the google frontpage.

Neat Machine
May 5, 2008

heh
Came across this in a networking class today while the teacher was just trying to demonstrate overflow:

C:
code:
char a[10];
char b[10];
strcpy(a, "Mary had a little lamb.");
strcpy(b, "Hello, World!");
puts(a);
puts(b);
This...worked. How did this worked? (There was no overflow, it printed just fine.) I can imagine how, conceivably, it might go. Perhaps the memory after a was not allocated so it just went ahead and threw the characters there and didn't complain (same with b). When puts() looks at a, it reads through but doesn't encounter a terminator until the end of "Mary had a little lamb." so it stops there instead of at a. I guess it makes sense that puts() doesn't recognize a strictly as a string to be terminated after 10 characters, but looks at a and prints until it hits a terminator (prints a string). But I mean...I just didn't expect it to happen like this. I really didn't think strcpy() would throw more than ten characters into a or b. How was this handled exactly? Am I just thinking about it incorrectly?

I guess it would have been worthwhile to try and access an eleventh element of a. That definitely would not have worked, right? ...right? I'm wondering if the fact that it's printing is more to do with puts() caring about a null terminated string more than it cares about a, and if it would have stopped sooner with printf(). The main problem, though, is that strcpy() was ok with putting more than 10 characters into a. That's really what's throwing me off.

Neat Machine fucked around with this message at 16:00 on Mar 1, 2012

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

Awesome Andrew posted:

This...worked. How did this worked? (There was no overflow, it printed just fine.) I can imagine how, conceivably, it might go. Perhaps the memory after a was not allocated so it just went ahead and threw the characters there and didn't complain (same with b). When puts() looks at a, it reads through but doesn't encounter a terminator until the end of "Mary had a little lamb." so it stops there. But I mean...I just didn't expect it to happen like this. How was this handled exactly?

I guess it would have been worthwhile to try and access an eleventh element of a. That definitely would not have worked...right?
Some speculations:
1. The string constants were allocated next to their respective arrays, and plowed over when as they were being copied from. If so, a second pass over that code should show corruption.
2. There was enough space put between a and b that there was no interference.

The most certain way is to view it in the debugger. Say, have it dump the member some bytes before and after "a" so you are sure you catch it all. It may have just organized it in memory so that there was enough room to catch the extra space--just dumb luck there. That simple code block might have worked but it's a ticking time bomb in a larger program.

Neat Machine
May 5, 2008

heh

Rocko Bonaparte posted:

Some speculations:
1. The string constants were allocated next to their respective arrays, and plowed over when as they were being copied from. If so, a second pass over that code should show corruption.
2. There was enough space put between a and b that there was no interference.

The most certain way is to view it in the debugger. Say, have it dump the member some bytes before and after "a" so you are sure you catch it all. It may have just organized it in memory so that there was enough room to catch the extra space--just dumb luck there. That simple code block might have worked but it's a ticking time bomb in a larger program.
This is pretty much how I was thinking about it, although a lot less educated. I have a question about this: In a larger program, how are those extra spots after "a" considered in memory? Are they allocated for "a", or otherwise secured? Might you expect to write over the (supposed-to-be)overflow with some other random variable later on? Those extra spots after "a", are they still 'empty' according to the program?

If it's considered empty, what happens when something tries to put new data there? Is it just replaced (now puts(a) gives something different) or is there some kind of conflict?

Vanadium
Jan 8, 2005

If it makes you feel better, it does crash compiled with clang. :)

Edit: Or with gcc -O3

From what I can tell, gcc just makes your char arrays a bunch bigger than you asked for.

Vanadium fucked around with this message at 16:19 on Mar 1, 2012

Duke of Straylight
Oct 22, 2008

by Y Kant Ozma Post
This is what gcc -S --no-builtin produces (by default it uses a built-in version of strcpy which would make the asm more confusing to read):

code:
        .file   "foo.c"
        .section        .rodata
.LC0:
        .string "Mary had a little lamb."
.LC1:
        .string "Hello, World!"
        .text
        .globl  main
        .type   main, @function
main:
.LFB0:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        subq    $32, %rsp
        movl    $.LC0, %edx
        leaq    -16(%rbp), %rax
        movq    %rdx, %rsi
        movq    %rax, %rdi
        call    strcpy
        movl    $.LC1, %edx
        leaq    -32(%rbp), %rax
        movq    %rdx, %rsi
        movq    %rax, %rdi
        call    strcpy
        leaq    -16(%rbp), %rax
        movq    %rax, %rdi
        call    puts
        leaq    -32(%rbp), %rax
        movq    %rax, %rdi
        call    puts
        leave
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE0:
        .size   main, .-main
        .ident  "GCC: (GNU) 4.6.2 20120120 (prerelease)"
        .section        .note.GNU-stack,"",@progbits
I'm not particularly educated in asm, but it seems that what gcc is doing is aligning the strings at 16 bytes, so that the "Hello, World!" is not quite long enough to overflow into the other one. Make the "Hello, World!" a little bit longer and it still won't crash (in gcc), but it will at least print something different than the exact strings given, make it longer yet and it will crash.

schnarf
Jun 1, 2002
I WIN.

Awesome Andrew posted:

Came across this in a networking class today while the teacher was just trying to demonstrate overflow:

C:
code:
char a[10];
char b[10];
strcpy(a, "Mary had a little lamb.");
strcpy(b, "Hello, World!");
puts(a);
puts(b);
This...worked. How did this worked? (There was no overflow, it printed just fine.) I can imagine how, conceivably, it might go. Perhaps the memory after a was not allocated so it just went ahead and threw the characters there and didn't complain (same with b). When puts() looks at a, it reads through but doesn't encounter a terminator until the end of "Mary had a little lamb." so it stops there instead of at a. I guess it makes sense that puts() doesn't recognize a strictly as a string to be terminated after 10 characters, but looks at a and prints until it hits a terminator (prints a string). But I mean...I just didn't expect it to happen like this. I really didn't think strcpy() would throw more than ten characters into a or b. How was this handled exactly? Am I just thinking about it incorrectly?

I guess it would have been worthwhile to try and access an eleventh element of a. That definitely would not have worked, right? ...right? I'm wondering if the fact that it's printing is more to do with puts() caring about a null terminated string more than it cares about a, and if it would have stopped sooner with printf(). The main problem, though, is that strcpy() was ok with putting more than 10 characters into a. That's really what's throwing me off.

In C, arrays can decay to pointers. When you call puts() there, puts() doesn't see a as an array of ten chars, it just sees an address in memory pointing to the beginning of a. It'll just keep writing until it hits the terminator. There's no checking, and in fact, there's no way for strcpy() to know how long it's safe to write for.

It definitely would work to try to access an eleventh element of a. If you're just reading from it, odds are you'd be fine. C doesn't do any bounds checking of arrays. The word "array" is maybe a little heavier than what C really does. When you type "char a[10];", you are asking the compiler to set aside 10 bytes on the stack for you, and "a" stores the beginning of that chunk of memory. It's not really storing the length of "a" anywhere; it's up to you to keep track of that. It's not 100% true that arrays are pointers, but in this case, that's how you should think of it. When you pass "a" to strcpy(), it gets no information about its length, just where it starts.

What happens if you write beyond the end of an array? It depends where the array is in memory. That depends on a bunch of things, including some practically random things that might vary each time you run your program. In this case, the arrays are on the stack. You might end up writing over other variables in your function. You might also do something crazier. There's a type of security vulnerability that can be exploited in this way. When you call a function, that function needs to store the address to jump back to when it returns. It puts that address somewhere on the stack, and if that gets overwritten with something else, rather than returning to where it came from, it'll jump to that address. It's possible to exploit programs that have these kinds of bugs by causing them to jump to somewhere else in memory that has code that does what the attacker wants.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
Man all of this talk reminds of an phone interview I think I bombed. They wanted to know what would happen if I returned a pointer to a stack variable in a function. I think the answer they wanted was "instant crash," but I told them instead was a ticking time bomb based on how it was compiled and the system's memory management rules. So I was trying to go through one way where it would crash the first time the referenced data was touched outside the function, and I don't think they wanted any of it. These folks weren't explicitly using x86 or some particular OS so I couldn't just peg it to one thing or another.

feedmegin
Jul 30, 2008

Rocko Bonaparte posted:

Man all of this talk reminds of an phone interview I think I bombed. They wanted to know what would happen if I returned a pointer to a stack variable in a function. I think the answer they wanted was "instant crash," but I told them instead was a ticking time bomb based on how it was compiled and the system's memory management rules. So I was trying to go through one way where it would crash the first time the referenced data was touched outside the function, and I don't think they wanted any of it. These folks weren't explicitly using x86 or some particular OS so I couldn't just peg it to one thing or another.

If that was actually the answer they wanted you probably didn't want to work there anyway. Given most systems (with virtual memory) use 4k pages and given most stack frames are small, an instant crash would actually be fairly unlikely if it was dereferenced right away.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Paniolo posted:

One last strange thing I found is that if you declare, but don't define, a copy constructor, you'll get a link error, even though it's never actually referenced anywhere in the generated code.

Aww, I missed an EH implementation question. At least I can still clear up this little mystery.

Short answer: MSVC stores a pointer to the copy constructor in global metadata associated with the thrown exception type.

Long answer: MSVC's C++ exceptions runtime is very "active", in the sense that a lot of the detail work of unwinding the stack and managing the exception object is managed directly by the runtime, rather than by extra code emitted for the function being unwound. For example, when you're unwinding through a call frame, you have to call all the destructors for locals and temporaries. In MSVC's design, the PC within a function being unwound is mapped to an entry within a "scope table" specific to that function and held in global constant memory; the table tells the runtime what nontrivially-destructible objects are active and what destructor to use for each; the runtime just walks that list and calls the destructors. As a contrasting example, the standard GCC/clang "personality function" turns that same PC into the address of a "landing pad" within the function; it then just resumes execution at that new address, trusting the function to do the right thing and then return control to the unwinder. (There are other huge differences, but it's this philosophical difference that's most relevant here.)

If you apply that philosophy consistently, it follows that the exceptions runtime should also be directly in charge of managing the catch variables. Since an exception might have class type, possibly including non-trivial copy constructors and destructors, the runtime has to know how to copy and destroy the object, just in case a function catches the exception by value. In fact, it has to know how to copy and destroy objects of every possible type that can catch the exception. This is all stored in global constant memory, emitted whenever you throw an exception of a specific type, and a pointer to it is passed as the second argument to CxxThrowException. It's the reference from this metadata that's presumably failing to resolve and giving you your linker error.

Interesting historical note: the fact that MSVC stores a pointer to the copy constructor with the exception and Itanium doesn't actually caused a pretty lively controversy during the design of C++11's std::exception_ptr. Some people were pushing for a guarantee that capturing an exception_ptr *had* to copy the exception. The MSVC people were happy with that because (1) they were already capturing the copy constructor and (2) they had to copy the exception anyway because it was allocated on the stack. We Itanium people were less pleased because it was impossible to satisfy that guarantee without breaking ABI, plus the copy isn't mandatory for us because we always heap-allocate exceptions. Eventually the committee picked language which let us maintain ABI but made some of the people pushing for exception_ptr kindof unhappy.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

rjmccall posted:

In fact, it has to know how to copy and destroy objects of every possible type that can catch the exception.
Every possible type that can be thrown as an exception? Or am I completely misunderstanding what you're saying.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Plorkyeran posted:

Every possible type that can be thrown as an exception? Or am I completely misunderstanding what you're saying.

Every type that can catch the exception. So if you've got throw iguana_exception();, the exception metadata emitted for type iguana_exception has information for how to copy-construct an iguana_exception, a reptile_exception, a vertebrate_exception, and an animal_exception, just in case you catch as one of these by value.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Oh, that makes sense. I was reading it as "every type that has a catch clause in one of its methods which could match it" which made zero sense.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
We're currently evaluating embedded C/C++ webservers at my job and I was wondering if anyone has any recommendations. One of the things we would like to be able to do is some form of long polling/Comet-style stuff. Granted, that's something that can be built on top of any web server, but I was wondering if there are any embedded servers that allow this to be done without too much fuss (i.e. I'd prefer not having to build the entire server-side of the Comet backend myself).

shrughes
Oct 11, 2008

(call/cc call/cc)

Sagacity posted:

We're currently evaluating embedded C/C++ webservers at my job and I was wondering if anyone has any recommendations. One of the things we would like to be able to do is some form of long polling/Comet-style stuff. Granted, that's something that can be built on top of any web server, but I was wondering if there are any embedded servers that allow this to be done without too much fuss (i.e. I'd prefer not having to build the entire server-side of the Comet backend myself).

I don't know what makes a server "embedded", but I think the canonical good C/C++ webserver right now is nginx.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

shrughes posted:

I don't know what makes a server "embedded"
Well, basically being able to link to a library that allows me to programatically say something like:

code:
server s("127.0.0.1", "8080");
s.get("/", "<html>hello</html>");
That kind of thing. But my question was if there are also any that natively support Comet-style applications and allow me to work with high-level Comet connections, instead of having to manage long-polling/websockets/etc myself.

MrMoo
Sep 14, 2000

I've just finished porting my own to C++ but I'm thinking of picking up the Chromium's test server instead as they have WebSocket support:

http://src.chromium.org/viewvc/chrome/trunk/src/net/server/

ComptimusPrime
Jan 23, 2006
Computer Transformer

Sagacity posted:

Well, basically being able to link to a library that allows me to programatically say something like:

code:
server s("127.0.0.1", "8080");
s.get("/", "<html>hello</html>");
That kind of thing. But my question was if there are also any that natively support Comet-style applications and allow me to work with high-level Comet connections, instead of having to manage long-polling/websockets/etc myself.

That is a really strange definition of embedded.

Anyway, all of the popular http daemons right now are written in C, including Apache, Comanche, Lighttpd and nginx.

But that code looks suspiciously like it came from Sinatra, and I think if you are going to be actually writing your code in C/C++ you are going to have a difficult time finding something that will allow you to define routes and views like that.

Paniolo
Oct 9, 2007

Heads will roll.
I recently did a project that required embedding a HTTP server and I used Mongoose. Worked well enough, and I think it will work just fine for Comet-style applications so long as the number of concurrent requests is fairly small. (It uses a one thread per request model, rather than being event driven, so with a lot of open requests you'd run out of threads for new connections after a while.)

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

ComptimusPrime posted:

That is a really strange definition of embedded.
How so?

I'm not saying it absolutely HAS to be that high-level. Paniolo's suggestion (Mongoose) also seems to work quite well. It's just that I was curious if there were any servers that allowed a higher level of abstraction (like, indeed, basic routing and auth) than raw HTTP.

I mean, there are plenty of solutions for other, admittedly higher-level, languages whereas there don't seem to be a lot of options for C/C++. In C# I can spin up a very simple HttpListener-based host and connect it to something like Nancy (a Sinatra clone) and I would have liked to have the same thing in C/C++ :)

Valtis
Sep 21, 2009
I have code that is something like this;

code:
// function 1 that initializes value; bar is class member
Foo *bar = &someRandomObject;

// function 2 that uses the pointer
std::cout << bar << std::endl; 

if (bar != nullptr)
{
    int value = bar->GetValue();
    // do stuff
}
If I comment out the std::cout line that prints the memory address, the bar->GetValue() returns random number (-2~ billion or so usually), if I leave the line uncommented, I get right values. I'm not entirely sure why this should happen, I'm currently thinking that somehow the object the pointer points at gets destroyed somehow despite the someRandomObject being passed as reference and generally existing until the program terminates.

Edit: VV Good point; here's the offending functions and the original calling function: http://pastebin.com/ABJKivHj (Keep in mind that I'm amateur so it may not make much sense from design perspective to implement the functionality like this)

Valtis fucked around with this message at 20:02 on Mar 11, 2012

Contero
Mar 28, 2004

So is there any standard/boost/decent variadic template version of sprintf yet? Or should I just stick with my snprintf wrapper?

That Turkey Story
Mar 30, 2003

Valtis posted:

I have code that is something like this;

We can't answer a question like this unless we see the actual code. "Something like this" is of little help. It could be any number of things. My guess is that the object holding the pointer is probably going out of scope, but without seeing your code we can't say for sure. Make a small test case that shows the behavior and post it.

Paniolo
Oct 9, 2007

Heads will roll.

Valtis posted:

If I comment out the std::cout line that prints the memory address, the bar->GetValue() returns random number (-2~ billion or so usually), if I leave the line uncommented, I get right values.

I didn't really dig into your code but often when you run into this kind of problem it's because the memory has already been freed but not overwritten; when you call cout, the iostreams library allocates a chunk of memory for its internal operations and that overwrites the old freed memory. The net effect is that it makes an operation which appears to not have any side effects look like it's modifying your object; in reality, you're just accessing unallocated memory

raminasi
Jan 25, 2005

a last drink with no ice

Sagacity posted:

How so?

To most people, "embedded server" means something more like "server running on an embedded system."

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

GrumpyDoctor posted:

To most people, "embedded server" means something more like "server running on an embedded system."
Ah. Sorry. :ohdear:

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Valtis posted:

code:
    for (auto skill : skills)

auto by itself will never infer as a reference type, so the type of skill here is Skill, not const Skill &. That means that initialization copies the vector element instead of binding a reference to it, so &skill ends up being the address of a local variable.

auto basically works via template argument deduction, though, so you can force it to bind by reference by writing auto &skill : skills instead.

shrughes
Oct 11, 2008

(call/cc call/cc)

Contero posted:

So is there any standard/boost/decent variadic template version of sprintf yet? Or should I just stick with my snprintf wrapper?

It depends on what the wrapper does (and if you have format string annotations and warnings turned on).

Valtis
Sep 21, 2009

rjmccall posted:

auto by itself will never infer as a reference type, so the type of skill here is Skill, not const Skill &. That means that initialization copies the vector element instead of binding a reference to it, so &skill ends up being the address of a local variable.

auto basically works via template argument deduction, though, so you can force it to bind by reference by writing auto &skill : skills instead.

Thank you. I probably should have realized that myself but sometimes I tend to be painfully blind to obvious issues.

TheAsterite
Dec 31, 2008
Hello, I'm taking a parallel and distributed class at my university where we have to make an algorithm work in parallel. In order to get started, we need to generate thousands of random x,y coordinates in a circle around 2 particular points. What's the best way to generate these numbers such that it's uniformly distributed inside that circle? We don't need to generate the numbers in parallel (thread safety and all that).

Edit: We're using c++

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
The easiest-to-implement way of doing something like that is to generate uniform x,y coordinates (which is easy), and then reject the ones that fall outside the circle.

Adbot
ADBOT LOVES YOU

That Turkey Story
Mar 30, 2003

Jabor posted:

The easiest-to-implement way of doing something like that is to generate uniform x,y coordinates (which is easy), and then reject the ones that fall outside the circle.

Or just generate one for angle and one for distance, each appropriately bounded to 2pi and r. No need to discard anything.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply