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
Standish
May 21, 2001

graffin posted:

I'm using it in C++, in the context of a template for a binary tree based dictionary. The object is an element in a node. In the dictionary, I'm trying to test the element to determine if it is an int or string.
http://codepad.org/cTLm8Woy

Standish fucked around with this message at 20:19 on Mar 20, 2008

Adbot
ADBOT LOVES YOU

Standish
May 21, 2001

lhunc posted:

I'm trying to get myself back into C but things are going a bit slow...

fwrite requires a pointer to a string as the first argument so how would I properly cast a character constant to a pointer? ie:

// Wrong
fwrite('\n', sizeof(char), 1, fd);

// Wrong
fwrite((char *) '\n', sizeof(char), 1, fd);
You cannot take the address of a literal so you'll have to assign it to a variable:
code:
char c = '\n';
fwrite(&c, sizeof(char), 1, fd);
Although it's probably simpler just to write a string consisting of a single character, like the other guy said.

Standish
May 21, 2001

csammis posted:

For starters, populate() takes a 1-D array and you're passing it a 2-D array :confused:
To continue, the function call should be "spf.populate(path);", no square brackets needed.

code:
void populate(int path[][1024]);
...
int path[1024][1024]; 
spf.populate(path);
(The reason you need to specify the second array dimension "[1024]" in the function prototype so that the compiler can do its pointer arithmetic magic properly and translate the array index "path[i][j]" to the memory address "path + (i * 1024 * sizeof(int)) + (j * sizeof(int) ".)

Standish
May 21, 2001

Milde posted:

If you're using gcc, you can use the -g switch which includes debugging info. If you run the program in gdb, or load a core dump from a debug build in gdb, it'll tell you the line numbers, and it'll even print snippets of the code if it can read the file from the path you compiled it from.
Or you skip the whole segfault->gdb->stack trace process and just compile with "-Wall -Werror" and it will warn you at compile time:
code:
 warning: format argument is not a pointer (arg 2)
In general, you should always have your compiler's options for "full warnings" and "warnings as errors" turned on.

Standish
May 21, 2001

vanjalolz posted:

Thats what I was thinking, but the unit is all about being atomic or something, like what happens if i have code like:

enablesignals()
// here.
pause()
disablesignals()

And theres a thread switch just after enable signals. The signal will be handled, then I will pause, and won't awake until the next signal.

edit:
I'm definitely doing something wrong. I think I'm meant to signal with semaphores.
Yeah, try doing sem_wait() instead of sleep(), and calling sem_post() in your signal handler (and set a variable as well if you need to know which specific signal it was):

code:
int s;
sem_t sem;
...
enablesignals();
sem_wait(&sem);
disablesignals();

...
void sighandler(int signo)
{
   s |= (1<<signo);
   sem_post(&sem);
}
Note that in general it's not safe to call arbitrary library functions (most notably printf) from within a signal handler, however sem_post plus a few dozen others are guaranteed safe under the POSIX standard. Best practice is to limit your signal handler to poking a semaphore and setting a global variable, then do all the actual signal-processing work in your main program code. Debugging signal-related deadlocks is not fun.

Standish fucked around with this message at 10:24 on May 11, 2008

Standish
May 21, 2001

Boz0r posted:

I'm trying to write a program that could cause my Windows XP computer to do a BSOD. This is apparently harder than I had imagined. Does anyone have a short code snippet that could do this?


With admin access. I'm just trying to kill my dell.

Could you give me a little more in-depth hint? I'm not too hot on C++ yet.
Not a program but http://support.microsoft.com/kb/244139 lets you generate a bluescreen without messing around with device drivers and kernel SDKs.

Standish
May 21, 2001

greatn posted:

Now this code pretty much works, except there is a phantom '1 put in at the end for some reason
Don't you need to null-terminate the "number" string?

Standish
May 21, 2001

abc[1].name is an array; you can't assign to it directly like that. You'll need to use strcpy() to copy "thing" into the array.

Or alternatively you could change "CandyBar::name" from an array into a pointer:
code:
struct CandyBar 
{ 
    [b]char *name;[/b] 
    double weight; 
    int calories; 
}; 
Explanation here.

Standish
May 21, 2001

For a start, use the [code ] tag.

code:
char foo[] = new char[50];

char* bar[] = new char*[50];
Arrays and pointers are not the same thing. "new char[50]" returns a char*; you cannot assign this pointer to an array name.
code:
While the following is okay:

char foo[] = "a string";
http://c-faq.com/aryptr/aryasgn3.html

Standish
May 21, 2001

slovach posted:

How the poo poo can I get the ID of a thread from another process? Is there no simple way to do this?
There is no way to do this using the C++ language and its standard libraries, it's platform-specific.

Standish
May 21, 2001

indigoe posted:

My experience with C is limited to `hello world` running in DOS with Turbo c++ sometime in the 90s, so I would appreciate if someone could point me in the right direction.

I have a burger processor script written in php (procedural) that is constantly running in a loop. When it's busiest, it can process about 5 burgers per second (BPS), but with the overheads it puts quite a strain on the server. It's not very scalable, and, after running over a year in production I'm sure it's as optimised as it can be. I need the process to handle 50 BPS without breaking a sweat, so I figured rewriting it in a more efficient language would be a great solution.

The requirements:
* Runs on linux (RHEL, fedora)
* Talks to mysql
* Makes http request (and needs to know response header code)

Will I need any special/nonstandard libraries? Anything I need to worry about if I want to be able to run it under different distros? Where do I begin?
You should begin by figuring out where the bottlenecks are in the PHP code and if rewriting in C++ will actually make any difference. (You'll probably find out that it's network/database bound not CPU-bound, as I can't imagine any calculation that would take 0.2 seconds of raw CPU numbercrunching time per individual burger.)

Anyway, if you do end up looking for C/C++ HTTP libraries, libcurl works very well although the API isn't the prettiest,

Standish fucked around with this message at 10:30 on Nov 28, 2008

Standish
May 21, 2001

hexadecimal posted:

what is a good library for C++ that is preferably cross-platform and would allow me to make HTTP-Requests?
libcurl

Standish
May 21, 2001

Avenging Dentist posted:

Put it in a vector or something.
Or just use std::string::append(const char*, size_t) to tell it explicitly how many characters to append:
code:
char cstr[] = {'t','e', 's', 't', '\0', 'f'};
std::string cppstring;
cppstring.append(cstr, 6);

Standish
May 21, 2001

Avenging Dentist posted:

That'll put the string in an inconsistent state.
How do you mean? Sure, you now have cppstring != cppstring.c_str() which can trip you up if you're not paying attention but that's not really "inconsistent"; what c_str() returns is quite clearly explained in the STL docs...

Standish fucked around with this message at 01:13 on Jan 3, 2009

Standish
May 21, 2001

csammis posted:

On Windows it'll only block the thread. This is why you do blocking I/O or heavy processing in a thread other than the UI thread, so the UI remains responsive to input while blocking is happening.

Windows threads are kernel threads, I'm not sure how user threads (like pthreads on Linux) work.
Linux pthreads are kernel threads too (or to be more exact, the Native Posix Thread Library which is the default implementation of the pthreads API on any non-ancient Linux is kernel-thread-based, and so was the LinuxThreads library which preceded it.)

Standish fucked around with this message at 22:12 on Jan 19, 2009

Standish
May 21, 2001

Fehler posted:

Can anybody explain to me why the delete[] here causes a heap exception? uinfo is a struct, uinfo.xx is a char* and yy is a wchar_t*.

code:
uinfo.xx = new char[wcslen(yy)];
wcstombs(uinfo.xx, yy, strlen(uinfo.xx));
delete[] uinfo.xx;
You haven't initialised the memory that uinfo.xx points to so strlen(uinfo.xx) will keep going until it reaches a null byte, potentially off the end of the array.

Edit: also wcslen() counts characters (not bytes) so if there's even one single character that requires two MBCS-encoded bytes then you'll overflow the uinfo.xx buffer.

Standish fucked around with this message at 15:19 on Jan 29, 2009

Standish
May 21, 2001

L:ordSilent posted:

Im sorry, I still don't quite get it. can someone kind of illustrate what file im supposed to include where? Im not sure how i can get the header file to use the functions in func.cpp without including it.
code:
// classtest.cpp
#include "func.h" // rename "Header1.h" to "func.h"; header files should have the same basename as the .cpp file they relate to
...
code:
// func.h (renamed from Header1.h)
// ... don't include any of your files
code:
 // func.cpp
#include "func.h"
...
Then just make sure your compiler is linking classtest.o and func.o together in the linker stage (compiler dependent and you haven't said which one you're using).

Standish
May 21, 2001

Injured Zebra posted:

Is there a way I can get input from the keyboard and set the enumeration to that?
Not directly, no. You could mess with the ASCII codes and do:
code:
TestSquare(grid,fish - 65,2);
but that's kind of ugly. Better to write something like the following to map all your input to valid enum values:
code:
letters inputToEnum(char ch)
{
  if ((ch >= 65) && (ch <= 80))
  {
    return static_cast<letters>(ch - 65);
  }
  else
  {
    // input out of range -- error handling
  }
}

Standish
May 21, 2001

You need to initialise your variables, also learn how to format your code properly and break your lines please.

Also spot the error in these lines:
code:
float PurchaseArray[6] = { 0, 0, 0, 0, 0, 0 };
...
for (int i = 0; i < 10; i++)
{
    PurchaseArray[i]=Sale;
}

Standish
May 21, 2001

Plastic Jesus posted:

In file some_consts.h I have
code:
const std::string MyString("blah");
By default variables have file scope, so every time you do #include "some_consts.h" you're creating a new copy of MyString with the scope of the file that includes it (remember #include is really really dumb and just does plain text substitution). If you output the address of the MyString objects:
code:
fprintf(stderr, "CLogger::CLogger(): Foo::MyString is '%s'@%p\n", Foo::MyString.c_str(), &Foo::MyString);

fprintf(stderr, "MyUtil::LookupValueBasedOnMyString(): Foo::MyString is '%s'@%p\n", Foo::MyString.c_str(), &Foo::MyString);
you can see that they're actually different objects.

It's blank because you're running into the static initialization order fiasco.

Solution is to declare (but not define) Foo::MyString in your header:
code:
extern const std::string MyString;
and then define it in exactly one of your cpp files:
code:
const std::string Foo::MyString("blah");

Standish fucked around with this message at 22:12 on Apr 2, 2009

Standish
May 21, 2001

ultra-inquisitor posted:

This'll be it. Isn't it a pointer to the vtable, though?
Are you on 64 bits?

Standish
May 21, 2001

code:
return fwrite(buffer, size, nmemb, out->stream);
Your CURLOPT_WRITEFUNCTION callback is supposed to return the number of bytes written. fwrite() returns the number of items written.

Also move the fopen() out of the callback so you can do proper error checking, it's possible that returning -1 from CURLOPT_WRITEFUNCTION is confusing it.

Standish fucked around with this message at 12:38 on Jun 23, 2009

Standish
May 21, 2001

ITIMER_VIRTUAL only increments while the process is actually running, not while it's blocked on io, try ITIMER_REAL instead.

Also printf() isn't safe to call inside a signal handler (and neither are most library functions in general, see man(7) signal).

Standish
May 21, 2001

There are three completely different string datatypes being talked about here:
  • The CString class, this is part of the Microsoft Foundation Classes and is not part of either the C or C++ standards
  • The std::string class, this is part of the C++ standard and is in the <string> header file
  • a "C string", this refers to a plain old zero-terminated array of bytes, from the original C language. It's built-in to the language so you don't need to include any header files to use it, but there are some related C standard library utility functions in the <string.h>/<cstring> header file

Standish
May 21, 2001

Mikey-San posted:

Hey guys, forgive me if this has been asked before, but let's say I have a number:

code:
4
And I want to remember the number somehow by calling it something else that isn't a number, and maybe vary the number later but keep the same name so it's easier for me to remember. How can I do that?

sorry this is impossible (there was a proposal for it in C++0x but it was cut)

Standish
May 21, 2001

Joe Kickass posted:

as when I call exec the 'child' program has no knowledge of any of 'parent's variables. Is there a simple way of doing this?
Children inherit their parents open file descriptors (this is a table in kernel not in userspace so it doesn't get overwritten by exec()), so if you do
code:
// parent 
int fd = open("/etc/passwd"); // "fd" has the value "42"
...
if (!fork()) exec("/some/child/process");
then if the newly exec()ed child process read()s from fd 42 it will get the contents of /etc/passwd.

That on its own doesn't do you much good because, as you point out yourself, how does the child know it's supposed to be reading from fd=42? so the other neat trick is where dup2() comes in:

most unix programs will by default get their input/output from 3 standard file descriptors: stdin(fd=0), stdout(fd=1) and stderr(fd=2). The dup2() system call lets you replace one of these standard file descriptors with your own file descriptor e.g.
code:
// parent
int fd = open("/etc/passwd"); // "fd" has the value "42"
dup2(fd, 0); // fd=42, 0=stdin
read(0, ...); // reading from stdin but data actually comes from /etc/passwd!
...
if (!fork()) exec("/some/child/process");
Now when the child thinks it's reading from stdin(fd=0), its input is actually coming from /etc/passwd, and this is all completely transparent to it.

Pipes are bit more complicated because it's all bidirectional and you can chain them arbitrarily but the same general stuff applies, call dup2() so that the read end of one pipe is duplicated to stdin and the write end of the next pipe in the chain is duplicated to stdout, then fork/exec.

Standish
May 21, 2001

Alman posted:

Alright, stupid assignment help, I'm retarded, why the gently caress do I keep segfaulting in the for loop here?
Run your program in a debugger, get a stack trace and dump the local variables? Nobody wants to debug your program by inspection, especially when you're providing it one post at a time.

Standish
May 21, 2001

RussianManiac posted:

Can somebody point me to the source file in kernel that is responsible for sending ACK packets?
net/ipv4/tcp.c

Standish
May 21, 2001

syphon posted:

code:
str = sprintf("%-4s", str);
Let me guess, you're coming from PHP, right?

Standish
May 21, 2001

code:
// scenemanager.h:
extern scenemanager sm; // this is a declaration of the "sm" variable
                 // you can have multiple declarations of the same variable 
                 // i.e. by including this header into multiple .cpp files

// scenemanager.cpp:
scenemanager sm; // this is the one and only definition of the "sm" variable
            // if you try to have multiple definitions you'll get a compile error

Standish
May 21, 2001

Subway Ninja posted:

Code
string str;
cout << "Name your vehicle: "
cin >> str;

DOS Window
Name your vehicle: Camero

Code
str.Wheels = 4; //str holds the value of 'Camero'
"str" is an object of class std::string. std::string has no "Wheels" member. You need a "Vehicle" class:
code:
// this is a class definition:
class Vehicle {
  public:
    int wheels;
    string name;
};
map<string, Vehicle> vehicles; // the Standard Template Library "map" class

// this is an *object* of the Vehicle class:
Vehicle myCar;
cout << "Name your vehicle: "
cin >> myCar.name;

myCar.wheels = 4;
vehicles[myCar.name] = myCar; //store the Vehicle object in the map

cout << "Which vehicle do you want to inspect? "
string tmp;
cin >> tmp;

map<string, Vehicle>::iterator iter = vehicles.find(tmp); // retrieve your Vehicle object from the map
// TODO: handle the case where the vehicle was not found
Vehicle v=iter->second;

cout << "A " << v.name<< " has " << v.wheels << " wheels.";

Standish
May 21, 2001

RussianManiac posted:

What exactly do you mean by "run strings against the program?"
code:

STRINGS(1)		     GNU Development Tools		    STRINGS(1)

NAME

       strings - print the strings of printable characters in files.

SYNOPSIS

       strings [-afov] [-min-len]
	       [-n min-len] [--bytes=min-len]
	       [-t radix] [--radix=radix]
	       [-e encoding] [--encoding=encoding]
	       [-] [--all] [--print-file-name]
	       [--target=bfdname]
	       [--help] [--version] file...

DESCRIPTION

       For  each  file	given,	GNU  strings  prints  the  printable character
       sequences that are at least 4 characters long (or the number given with
       the  options  below)  and are followed by an unprintable character.  By
       default, it only prints the strings from  the  initialized  and	loaded
       sections  of  object  files;  for  other  types of files, it prints the
       strings from the whole file.

       strings is mainly useful  for  determining  the	contents  of  non-text
       files.

Standish
May 21, 2001

"*(array+MAX)" is equivalent to "array[MAX]" which is the same as "array[4]" which is one off the end of the array (the declaration is "int array[4]" which means valid indices are from 0 to 3).

Standish
May 21, 2001

Bakkon posted:

I'm in a parallel programming course (we use the MPI API if anyone's curious) and for our final project, we get to pick a topic of our choice and implement it using multiple cores. I'm just looking for suggests on a potential algorithm that would be neat/fun/interesting to look into, preferably something processor intensive that would show noticeable difference when ran in parallel.
Ray tracing?

Standish
May 21, 2001

LockeNess Monster posted:

Any time you allocate something with either new or malloc you need to make sure you delete it if you are no longer going to use the buffer/object.
To clarify this, you should:
  • free() memory allocated with malloc()
  • delete memory allocated with new
  • delete[] memory allocated with new[]
i.e. calling delete on a pointer allocated with malloc(), or delete on a pointer allocated with new[] is undefined behaviour.

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.3

Standish
May 21, 2001

LockeNess Monster posted:

Do standard malloc and free usually use sbrk underneath somewhere? Or is most of this just unspecified so I should just not gently caress with mixing new/malloc delete/free?
There's really no "standard" implementation of malloc, a lot of them use the heap/sbrk for smaller allocations and mmap(MAP_ANONYMOUS) for larger chunks.

Edit: you can read about dlmalloc here, that's what the glibc malloc is ultimately based on

Standish fucked around with this message at 22:09 on Mar 9, 2010

Standish
May 21, 2001

korofrog posted:

I'm fine with using 0, I was just wondering if it could be done.
http://c-faq.com/aryptr/non0based.html

Note that if you actually do this and I end up having to maintain your code I will track you down and kill you.

Standish fucked around with this message at 14:28 on Mar 10, 2010

Standish
May 21, 2001

Genpei Turtle posted:

Is it possible for the same variable to occupy two different locations in memory and if so how would that sort of situation come about?
I suppose you could mmap() or shmat() the same file/shared memory segment at two different addresses? If you were doing this you'd know it, so you probably have some other scope/memory corruption problem going on, impossible to tell without code...

Standish
May 21, 2001

Jose Cuervo posted:

Thanks, that worked. Is there something else you suggest using instead of iostreams?

use the C stdio stuff -- fopen(), fread(), fgets(), printf(), fprintf() (but not gets()).

Adbot
ADBOT LOVES YOU

Standish
May 21, 2001

Ledneh posted:

Another optimization question. Say I have a program that, for simplicity's sake, uses one string literal (say, "pants") but constructs that literal as a std::string over and over (and over and over :suicide: ) again in code. This happens because my predecessors hate me.

Is it likely to gain me anything in the real world if, instead of repeatedly constructing that same literal, I wrap it in a class that goes something like this contrived-as-hell pseudocode?
Yes, this is a fairly widespread pattern called string interning.

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