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
MrMoo
Sep 14, 2000

I would hazard if Element is packed by compiler attributes the struct wrapper would promote to machine alignment.

Adbot
ADBOT LOVES YOU

shrughes
Oct 11, 2008

(call/cc call/cc)
It is guaranteed if you write

code:
enum { StructSizeofAssertion = 1/(sizeof(Struct) == sizeof(Element)) }

Matazat
Aug 12, 2011

I'm looking to learn the basics of C++ this summer and I'd like a nice book to help me along the way. Anyone have any recommendations? I know there's probably free stuff on the Internet, but I still want a book. I was looking at this one since the reviews are good and it was published in October 2011, so it's probably pretty up to date. I know the basics of Java, so I don't need an introduction to programming or anything. I'm okay with spending up to $50.

shrughes
Oct 11, 2008

(call/cc call/cc)

Matazat posted:

I'm looking to learn the basics of C++ this summer and I'd like a nice book to help me along the way. Anyone have any recommendations? I know there's probably free stuff on the Internet, but I still want a book. I was looking at this one since the reviews are good and it was published in October 2011, so it's probably pretty up to date. I know the basics of Java, so I don't need an introduction to programming or anything. I'm okay with spending up to $50.

Koenig & Moo.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

tractor fanatic posted:

Do I get some kind of guarantee in C++ that

code:
struct Struct{
    Element e;
};

sizeof(Struct) == sizeof(Element)
as long as Struct doesn't have any kind of virtuals?

No (there could be padding tacked on), but you do get a guarantee that the address of the struct and that of its first element are the same

Rottbott
Jul 27, 2006
DMC

shrughes posted:

It is guaranteed if you write

code:
enum { StructSizeofAssertion = 1/(sizeof(Struct) == sizeof(Element)) }
Also in newer compilers you can use static_assert() for this.

CPFinnit
Jun 5, 2008
I've been wracking my brain on this problem all afternoon. I need to write a program that calculates pi using the formula pi = 4 - 4/3 + 4/5 - 4/7...

Easy enough. The problem I keep running into is my loop always runs a final time after my counter is equal to my loop parameter.

code:
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

/*
Function returns an integer value entered by the user.  The prompt changes depending on which string is handed off to the function.
User input is only accepted it the value is larger than zero.  A negative number or zero will result in the function prompting for another input.
*/
int userinput (string message)
{
    int terms;
    bool validNum = false;

    cout << message;

    while (!validNum)
    {
        cin >> terms;

        if (terms > 0)
            validNum = true;

        else
            cout << "Invalid response.  Please enter a non negative non zero integer: ";
    }

    return terms;
}

int main()
{
    int count = 1; //Loop counter.
    int displayCount = 0; //Loop counter for displaying the value of pi at the nth calculation.
    int piTerms; //The number of terms used to calculate pi.
    int piDisplay; //The value at which pi will be displayed.
    int denm = 3; //The value of the denominator in the pi calculation.
    double pi = 4.0; //The original value of pi.

    //The following strings are used with the above function to prompt for either the number of terms or the nth value to be displayed
    string termsMessage = "Please enter the number of terms used to calculate pi: ";
    string displayNumMessage = "After how many calculations should the answer be displayed? ";

    //Sets the value of the two integers based on the value returned from the user function
    piTerms = userinput(termsMessage);
    piDisplay = userinput(displayNumMessage);

    cout << "Results:" << endl << endl;


    //The following loop runs until the counter is equal to the number of terms entered by the user.

    while (count <= piTerms)

    {
        //This portion of the loop displays the value of pi everytime the loop counter is equal to the value entered by the user.
        //Once it is equal, the counter is reset so that it will display the value of pi to 9 places every nth calculation.
        displayCount ++;
        if (displayCount == piDisplay)
        {
        cout << fixed << setprecision(9) << setw(4) << count << ": Pi = " << pi << endl;
        displayCount = 0;
        }

        /*
        Because the formula alternates between adding and subtracting the value (4/n+2) the following section
        either adds or subtracts a value based on whichever iteration of the loop it is currently on.
        the first calculation is always substraction so if the nth position is odd, the loop subtracts (4/n+2).
        If the value is even, the loop adds (4/n+2).
        */
        if (count % 2 != 0)
        {
            pi -= (4.0 / denm);
            denm += 2;
        }
        else
        {
           pi += (4.0 / denm);
           denm += 2;
        }



        count++; // Increases the loop counter by one each pass.

    }

    //Outputs the final value of pi to 9 places.
    cout << endl;
    cout << fixed << setprecision(9) << "Final Pi = ";
    cout << pi << " " << count << endl;


    return 0;
}
Essentially I need the final value of pi to be the nth calculation as entered by the user but I keep getting the nth + 1 value. I'm sure I'm missing something obvious, but I can't figure out what that is.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

jhunter46 posted:

Essentially I need the final value of pi to be the nth calculation as entered by the user but I keep getting the nth + 1 value. I'm sure I'm missing something obvious, but I can't figure out what that is.

The first term is just 4, right? So you need the loop to run once if piTerms == 2, twice if piTerms == 3, and not at all if piTerms == 1. But count starts at 1, and the if condition is count <= piTerms.

nielsm
Jun 1, 2009



Off-by-one errors are often caused by a comparison operator not being sharp when it should be, or being sharp when it shouldn't.
Check your loop condition.

CPFinnit
Jun 5, 2008
I think I just had to sleep on the problem.

I changed the algorithm and instead of using modulus division, I used a flipping Boolean. In addition my loop was treating n0 as n1 which it shouldn't because a 0 iteration loop is prohibited by the input restrictions. I also moved the portion of the loop that read the value of pi every nth time to after the calculation had been complete.

My final output doesn't perfectly match what we were given as an example, but that loop was also treating n1 as n0, which isn't correct.

Thanks!

raminasi
Jan 25, 2005

a last drink with no ice
I'm pulling my hair out here
C++ code:
    EXPECT_FALSE(pair.is_self());
    EXPECT_FALSE(pair.are_perpendicular());
    EXPECT_TRUE(parallel_clauses());
    EXPECT_TRUE(nonparallel_clauses());
    EXPECT_TRUE(
        !pair.is_self() &&
        !pair.are_perpendicular() &&
        parallel_clauses() &&
        nonparallel_clauses());
The first four tests pass and the last one fails :psyduck: Am I just being completely retarded about something? Found it, one of the predicates is changing its return result for some reason. Still confusing as hell the first time around.

raminasi fucked around with this message at 20:20 on Jun 9, 2012

IratelyBlank
Dec 2, 2004
The only easy day was yesterday
I have a question specifically about Visual Studio. Is there something I am missing that I need in order to get more friendly tooltips? Here is an example:



In C# this would have maybe a short description of what this function does and some more decipherable parameters. Does such a thing exist for C++?

cr0y
Mar 24, 2005



Does an image processing algorithm exist that can take a black white image and perform some sort of hashing on it that will.produce the same output "hash" regardless of whether or not the image is a perfect copy of the original. My interest is in the error tolerance of biometric finger print scanners and how they can pass/fail a scan given the inherent "fuzziness" of the input data.

Any input on this or how biometric auth works would be rad.

IratelyBlank
Dec 2, 2004
The only easy day was yesterday

cr0y posted:

Does an image processing algorithm exist that can take a black white image and perform some sort of hashing on it that will.produce the same output "hash" regardless of whether or not the image is a perfect copy of the original. My interest is in the error tolerance of biometric finger print scanners and how they can pass/fail a scan given the inherent "fuzziness" of the input data.

Any input on this or how biometric auth works would be rad.

I did something similar recently, and I followed something roughly similar to what these guys did: http://phash.org/ except I averaged colors based on a grid where I expected certain things to be.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Assuming you have two true black and white bitmaps (literally one bit per pixel), you already have a "hash". You can find the differences between the two hashes, and set rules about tolerance in the domain of fingerprints. A bit of research on fingerprints should show you the most important parts of fingerprints, of which you have little tolerance between images.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Actually, for fingerprints, look at the work the NIST has done with their latent fingerprint system and biometric image software.

raminasi
Jan 25, 2005

a last drink with no ice

IratelyBlank posted:

I have a question specifically about Visual Studio. Is there something I am missing that I need in order to get more friendly tooltips? Here is an example:



In C# this would have maybe a short description of what this function does and some more decipherable parameters. Does such a thing exist for C++?

Are you asking about creating them for your own code, or the standard library? Visual C++ supports documentation comments, and comments you put on the line above or the same line after seem to get automatically slurped into the tooltips if you've got nothing else (this is something that I've just noticed, not done exhaustive testing on, and I don't know what happens if you have both). I think for the standard library you're out of luck, though.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

cr0y posted:

Does an image processing algorithm exist that can take a black white image and perform some sort of hashing on it that will.produce the same output "hash" regardless of whether or not the image is a perfect copy of the original. My interest is in the error tolerance of biometric finger print scanners and how they can pass/fail a scan given the inherent "fuzziness" of the input data.

Any input on this or how biometric auth works would be rad.

You might want to play around with phash/perceptual hashes - http://phash.org.

cr0y
Mar 24, 2005



hieronymus posted:

You might want to play around with phash/perceptual hashes - http://phash.org.

Cool, I will definitely start playing with this (anyone else feel like the biggest nerd on the planet when they realize "dude this is so awesome an algorithm to compare dissimilar images! :c00l: ".

On that note, is there any way that I can capture a finger print scan from a common laptop finger print reader (the kind with the little strip of gold metal). I don't have enough of an understanding as to what the device is actually sending to the machine. I sniffed the usb traffic (which is how it interfaces) but don't seem to be getting anything useful. I am thinking the chip in the device might be doing it's own analysis and simply sending a pass/fail to the host system, but am not sure.

or some other non-technical way of digitizing my own fingerprint?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Don't use perceptual hashes for fingerprints. You need to use something to detect minutiae.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip
I'm seeing some weird behavior with snprintf on ARM. I have a call that looks like this:

C++ code:
int foo_to_string(struct foo *f, char *buf, int buflen)
{
    //... 
    snprintf(buf, buflen, "... %f, ...", f->some_float_member);
    //...
}
(C rather than c++, but there doesn't seem to be syntax highlighting for plain c)

When the snprintf call is made inside the function with the %f format specifier, it either fills in nothing for that part of the format string or a bunch of zeroes regardless of the value passed for that slot in the format (even literals like 3.14f). When an identical call is made in main, it works as expected. When format specifiers other than %f are used, it works as expected either when called from main or from inside the other function. What is it most likely that I've blown up? I rather doubt that I've found such a basic bug in glibc for ARM.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Otto Skorzeny posted:

What is it most likely that I've blown up?
Is the function in a different file from main? If so it's possible that "struct foo" has ended up packed differently in the two files, which might be remedied with an appropriate #pragma pack in the header that declares the struct.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

roomforthetuna posted:

Is the function in a different file from main? If so it's possible that "struct foo" has ended up packed differently in the two files, which might be remedied with an appropriate #pragma pack in the header that declares the struct.

I will investigate this, but I don't think it fits the data well. I may not have been explicit enough earlier, but when I swap in a literal like this:

C++ code:
int foo_to_string(struct foo *f, char *buf, int buflen)
{
    //... 
    snprintf(buf, buflen, "... %f, ...", 867.5309f);
    //...
}
it still works correctly in main and wrongly in foo_to_string. Honestly I'm baffled, especially since it seemed to be working and passing tests this morning but blew up this afternoon when I don't think I even touched the definition of foo_to_string in the meantime.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Try swapping foo_to_string out for that line alone, and make sure it gets called. And then print the buffer immediately after.

pseudorandom name
May 6, 2007

Is it actually calling snprintf()? A quick Google suggests that the ARM compiler will rewrite printf calls to different functions depending on whether or not you're passing them float arguments.

http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka3933.html

yippee cahier
Mar 28, 2005

Sure it's a float and not being converted to a double? What happens with "%lf"?

shrughes
Oct 11, 2008

(call/cc call/cc)
That's not the problem, C will upconvert floats to doubles when passing them to variable argument lists. %f is the format specifier that prints a double.

raminasi
Jan 25, 2005

a last drink with no ice
I'm only suggesting this because you seem relatively well into "what the everloving gently caress territory," but I've had success fixing bugs that weird by just blowing all my intermediate files away and rebuilding the entire binary from scratch (assuming you haven't done that yet).

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

GrumpyDoctor posted:

I'm only suggesting this because you seem relatively well into "what the everloving gently caress territory," but I've had success fixing bugs that weird by just blowing all my intermediate files away and rebuilding the entire binary from scratch (assuming you haven't done that yet).

._. I just did this and poo poo works again. What the hell, PSoC Creator/ARM gcc 4.4.1?

Space Kablooey
May 6, 2009


What's the point of code like this?

code:
if(remove("settings.xml")==-1);
I mean, there is no code for neither of the possible results and there is no more code after this on the function. It is inside a destructor, though.


If you aren't going to do anything with the value, why not write

code:
remove("settings.xml");
already?

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
A dumb way to silence unused return value warnings, perhaps. Probably just bad code.

Space Kablooey
May 6, 2009


But then Visual Studio complains about "Empty controlled statements"... Thanks.

Slashrat
Jun 6, 2011

YOSPOS
I'm trying to get started on using OpenCL, but ran into trouble getting a sanity-friendly overview of what I need to write code that will run on any OpenCL-capable hardware. I looked at the SDKs on offer from the big three (Nvidia, AMD, Intel), but found them all ambiguous on whether any code written with them would actually work on hardware from the other manufacturers. The Nvidia CUDA toolkit in particular doesn't give any indication of being helpful for anything other than CUDA programming. Google searches hinted that there was once an Nvidia OpenCL SDK available at http://developer.nvidia.com/opencl, but it seems to have vanished since then in that case.

Anyone want to help me make sense of this and perhaps point me in the direction of a good OpenCL sdk (for windows/VS2010)?

Paniolo
Oct 9, 2007

Heads will roll.
The CUDA Toolkit includes nVidia's OpenCL libraries. I'm pretty sure you have to compile against the hardware vendor for the target machine, so if you need to support both nVidia and ATI cards you'll have to provide binaries for both, or provide source and have your customers build it themselves.

If you're on Windows exclusively you could look into DirectCompute (or C++ AMP, which is built on it) which will work without recompilation on both vendors.

If this is just a learning project then just grab the SDK from your video card's manufacturer and go nuts.

Slashrat
Jun 6, 2011

YOSPOS
Thanks!

I'm doing an implementation of the water and erosion simulator that From Dust also used to serve as the basis for my thesis project, but I'd also been aiming at making it robust enough to be useful to others since there didn't seem to be any existing open source implementations of it.

I guess I'll go with the CUDA toolkit for now in the name of expediency.

Slurps Mad Rips
Jan 25, 2009

Bwaltow!

Paniolo posted:

The CUDA Toolkit includes nVidia's OpenCL libraries. I'm pretty sure you have to compile against the hardware vendor for the target machine, so if you need to support both nVidia and ATI cards you'll have to provide binaries for both, or provide source and have your customers build it themselves.

If you're on Windows exclusively you could look into DirectCompute (or C++ AMP, which is built on it) which will work without recompilation on both vendors.

If this is just a learning project then just grab the SDK from your video card's manufacturer and go nuts.

Most of the vendor's out there follow the Installable Client Model (icd) extension, which allows you to query all available opencl platforms on a given machine, whether they are from the same vendor or not. You simply need to install their runtime for it to work.

You can read more about it here. It gives a few examples, but AFAIK Intel, AMD, and Nvidia all follow the ICD.

Contains Acetone
Aug 22, 2004
DROP IN ANY US MAILBOX, POST PAID BY SECUR-A-KEY

Contains Acetone fucked around with this message at 17:51 on Jun 24, 2020

seiken
Feb 7, 2005

hah ha ha
Is there a reason a CGI program written in C++ (even very basic "hello world") would work perfectly on the server when compiled with optimizations off, but give a 500 Internal Server Error with -O1 or anything more? It runs fine on my local machine with either option. I'm compiling on the same architecture as the server (x86-64 linux). Does g++ do optimizations that are only valid for my [distribution/processor/kernel/something else] or something? Am I naive to expect it to work without compiling it directly on the server? (getting shell access is possible but a bit of a hassle. It's probably not actually a big deal to just leave optimizations off but now I'm curious)

seiken fucked around with this message at 15:19 on Jun 16, 2012

schnarf
Jun 1, 2002
I WIN.

seiken posted:

Is there a reason a CGI program written in C++ (even very basic "hello world") would work perfectly on the server when compiled with optimizations off, but give a 500 Internal Server Error with -O1 or anything more? It runs fine on my local machine with either option. I'm compiling on the same architecture as the server (x86-64 linux). Does g++ do optimizations that are only valid for my [distribution/processor/kernel/something else] or something? Am I naive to expect it to work without compiling it directly on the server? (getting shell access is possible but a bit of a hassle. It's probably not actually a big deal to just leave optimizations off but now I'm curious)

Issues that only appear when optimization is on usually mean a bug in your code that didn't manifest itself without optimizations. For example, in this fragment of code:
code:
void f(int* p) {
    *p= 5;
    g();
}
If the optimizer inlines a call to f(), and can prove that f() is getting called with a null pointer, it's entitled to never call g(), because it knows that first it dereferences a null pointer, which is undefined behavior. If you're interested in this, check out this series of articles: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html

It shouldn't be doing optimizations that are only valid on your local machine, so I doubt it's that -- you should totally be able to compile on your machine.

Adbot
ADBOT LOVES YOU

xgalaxy
Jan 27, 2004
i write code
So I don't understand why there is no way to specify a deleter for allocate_shared.
I'm trying to decide if I should care or not.

What I'm doing is I've written my own specialized allocators that, in summary, basically allocates a pool of memory up front. And under certain compile conditions keeps track of some memory stats, etc.

Now, make_shared / allocate_shared main advantage is that they create the shared pointer, the bookkeeping, and the object in one allocation. Which is a decent optimization. But there is no way to give these factories a deleter which makes them useless for what I want to do.

But again, I'm not sure if I should care.
The main advantage of my allocators is that the memory is allocated up front, so there should be minimal impact when I create a new object since I don't have to do dynamic memory allocation at that moment.

With that in mind does it matter that by not using allocate_shared I will be requesting memory from my allocator in two distinct steps by using the shared_ptr directly to specify the allocator and deleter? I guess I should benchmark it but my gut feeling is that since my memory is allocated up front the two distinct memory requests won't be such a big deal as it normally would be.

I just can't help feeling like I'm being denied the opportunity of having all that space reserved in one call.

xgalaxy fucked around with this message at 17:33 on Jun 16, 2012

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