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
OddObserver
Apr 3, 2009

Mopp posted:

Yes, I'm doing this according to instructions and were told to use pointers. Shouldn't the constructor still be called?


edit: or rather, calc.h has an "VariableTable* table" declared, but I was unsure how to proceed from there. How do I assign an VariableTable to T in an correct way then?

You never create the object. It's an uninitialized pointer pointing to some (sorta) random location (which may not even be) in memory.

Adbot
ADBOT LOVES YOU

Mopp
Oct 29, 2004

OddObserver posted:

You never create the object. It's an uninitialized pointer pointing to some (sorta) random location (which may not even be) in memory.

I assume this is the source of the segfault. Sorry for all the beginner questions, but how do I create the object and then make a pointer to it?

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!
More to the point from what pseudorandom name said, it's not even a pointer to a VariableTable, it's an uninitialised pointer to type VariableTable.

If you have a preexisting table you want to point to, then T=&othertable;
If you are wanting to make a new table then T=new VariableTable;

(And then you'll also need to delete T;, or whatever pointer ends up storing that address, at some point.)

Mopp
Oct 29, 2004

Alright, that did it. Thanks for the help!

My other question remains, that I want to be able to input commands to a prompt in two different ways. First as a single char, ie. 'X' and then as a ie. "X n" where n is an int. As it works right now, the program opens a cin, reads a char into command_, check if it's valid and then executes it. Is there a smart way to handle this, or should I use getline and store the command into a string, load the first character as command and if there is a digit following, use that as a parameter?

POKEMAN SAM
Jul 8, 2004

Mopp posted:

Alright, that did it. Thanks for the help!

My other question remains, that I want to be able to input commands to a prompt in two different ways. First as a single char, ie. 'X' and then as a ie. "X n" where n is an int. As it works right now, the program opens a cin, reads a char into command_, check if it's valid and then executes it. Is there a smart way to handle this, or should I use getline and store the command into a string, load the first character as command and if there is a digit following, use that as a parameter?

What you probably want to do is called tokenization. You'll probably want to just read an entire line and tokenize it on spaces. The simple way is to just split the string into two when you see a space, but there are smarter ways that cover more cases. Then, when you see an "X" you call the X function and pass the (possibly empty) array of arguments to it, so the X function can decide what to do based on the count/value of the arguments.

PapaLazarou
May 11, 2008

Decadent Federation Swine!

pseudorandom name posted:

Probably because the server only wants one request per connection.

edit: Also, why are you rolling your own HTTP client instead of using one of the many excellent libraries out there?

Need to roll my own for this project, as related to me by my manager. Not using any libraries outside of gnu c. Even if I comment out the original request, it gives me the same Connection: close. Also I don't send anything after that in the original tcpdump.

Ziir
Nov 20, 2004

by Ozmaugh
I'm taking a parallel programming for scientific computing course right now and the primary language used in all exercises will be C. Problem is, I don't know C. I know MATLAB/GNU Octave fairly well backwards and forwards and have some experience with Fortran in previous research. I just need some basic understanding of C and fast, so I'm looking for some kind of crash course exercise/tutorial into C with emphasis on scientific computing/number crunching.

Can anyone recommend me some kind of tutorial or online book that will teach me the basics of what I need to know?

HFX
Nov 29, 2004

Ziir posted:

I'm taking a parallel programming for scientific computing course right now and the primary language used in all exercises will be C. Problem is, I don't know C. I know MATLAB/GNU Octave fairly well backwards and forwards and have some experience with Fortran in previous research. I just need some basic understanding of C and fast, so I'm looking for some kind of crash course exercise/tutorial into C with emphasis on scientific computing/number crunching.

Can anyone recommend me some kind of tutorial or online book that will teach me the basics of what I need to know?

C is going to be a painful language to learn to parallel program with if this is your first introduction to the C language. You can always start with the C Language book by K&R. It's kind of the defacto learning guide to C. You can learn the syntax in about a week from the book even if you have never programmed in a C like procedural language before. However, you may struggle at times. The really hard part will be when you try to parallelize. The OS you are running on will influence how you go about doing this as threading support is done through library calls (POSIX / Win32 API) or parent / child processes (another way of doing it in Unix). Maybe some of the other guys can recommend some libraries to make threads, semaphores, mutex's, etc easier to use.

Ziir
Nov 20, 2004

by Ozmaugh

HFX posted:

C is going to be a painful language to learn to parallel program with if this is your first introduction to the C language. You can always start with the C Language book by K&R. It's kind of the defacto learning guide to C. You can learn the syntax in about a week from the book even if you have never programmed in a C like procedural language before. However, you may struggle at times. The really hard part will be when you try to parallelize. The OS you are running on will influence how you go about doing this as threading support is done through library calls (POSIX / Win32 API) or parent / child processes (another way of doing it in Unix). Maybe some of the other guys can recommend some libraries to make threads, semaphores, mutex's, etc easier to use.

Unfortunately I have no choice in the matter because I must take this course. I don't need to learn parallel programming on my own (that's what the class is for), but I do need some basic understanding of C.

Mopp
Oct 29, 2004

I came across an odd error today which I have no idea how to debug. I'm still doing my calculator, and I'm trying to finish up on it, but when I add the destructor, and I get this error:

code:
pure virtual method called
terminate called without an active exception
Abort
I have localized the error to the destructor which looks like this:
code:
//expr.cc
Expression::~Expression() { delete expression_; }  // ExpressionTree* expression_ is a private member
//exprtree.h
class Operator : public ExpressionTree {   // ExpressionTree har virtual destructor
 public:
  void print(ostream&, int) const;
  ~Operator();
protected:
  Operator(ExpressionTree*, ExpressionTree*); 
  Operator(const Operator&);
  ExpressionTree* lchild_;
  ExpressionTree* rchild_;
};
//exprtree.cc
Operator::~Operator() {
  delete lchild_;
  delete rchild_;
  }

I'm new to debugging, and this error isn't giving me much to work with. I have no idea why the destructor is called, so what should I do?

edit: apperently reassigning operator= solved this, no idea why though.

Mopp fucked around with this message at 19:11 on Oct 13, 2010

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
The problem was almost certainly a double-delete, i.e. you deleted the same object twice. Since your memory policy seems to be that an Operator owns its children, then the default copy-assignment operator is going to leave two objects owning the same children, which is obviously bad. So if you redefined the copy-assignment operator to copy the children, that's why your problem went away.

I'm just speculating here, though.

rjmccall fucked around with this message at 21:22 on Oct 13, 2010

Jose Cuervo
Aug 25, 2004
I am having a problem with memory management - where my computer runs out of memory when running my code. I suspect I have a memory leak and so I have been checking through my code to see that I have as many delete instances as I have new instances.

The one place I am not sure is the following:
code:
for (ScheduleBlock *b= jobList[i]->head; b!= NULL; b= b->nextBlock)
     jobListCopy[nonEmptyMachinesCtr]->addBlock(b->jobID, b->startTime, b->processTime, b->ESTime, b->LFTime);
The code for ScheduleBlock is:
code:
ScheduleBlock::ScheduleBlock() {

	jobID= 0;
	startTime= 0;
	processTime= 0;
	ESTime= 0;
	LFTime= 0;
	nextBlock= NULL;
}


ScheduleBlock::~ScheduleBlock() {

	nextBlock= NULL;
	std::cout<< "Schedule block deleted" << std::endl;
}
When I run the code, the line Schedule block deleted does not print out on the screen, leading me to believe that b is never being deleted, and is my memory leak.

Even when I change the code to
code:
ScheduleBlock *b;

for (b= jobList[i]->head; b!= NULL; b= b->nextBlock)
     jobListCopy[nonEmptyMachinesCtr]->addBlock(b->jobID, b->startTime, b->processTime, b->ESTime, b->LFTime);

delete b;
the line Schedule block deleted does not print. Any help?

Vanadium
Jan 8, 2005

When the for-loop is over, b equals NULL because that is when the for-loop stops. Using delete on NULL is defined to not do anything, in particular it will not call the destructor.

Edit: I cannot tell where your memory is. You need to use delete on pointers when they point to objects that you want to deallocate, not on pointers in general.

Jose Cuervo
Aug 25, 2004

Vanadium posted:

When the for-loop is over, b equals NULL because that is when the for-loop stops. Using delete on NULL is defined to not do anything, in particular it will not call the destructor.

Edit: I cannot tell where your memory is. You need to use delete on pointers when they point to objects that you want to deallocate, not on pointers in general.

Are you saying that the memory that was allocated to ScheduleBlock b is deallocated after the for loop is done because the pointer points to NULL, or are you saying that because it points to NULL the destructor does not get called and thus the memory being used by Is this saying that the memory allocated to ScheduleBlock b is not deallocated?

I have put the other piece of code that I wrote using pointers on pastebin over here. I went over it, but I cannot see where it would be leaking memory.

I would appreciate it if anyone could tell me if the way I wrote it leaks memory or how to check that it does. I have been looking into using something like Valgrind, but I have been frustrated so far.

EDIT: The .h file is below:

code:
#include<iostream>
#include "ScheduleBlock.h"

class MachineSchedule
{
public:
	MachineSchedule();
	virtual ~MachineSchedule();

	void deleteBlock(ScheduleBlock *delBlock);  //deletes a block in the schedule
	void printSchedule(void);
	void dueDateOrder(MachineSchedule &machSchedule);

	//adds a block to the end of the machine schedule
	void addBlock(int jobID, long int startTime, int processTime, long int ESTime, long int LFTime);
	//inserts a block into the middle of the machine schedule
	void insertBlock(int jobID, long int startTime, int processTime, long int ESTime, 
		long int LFTime, ScheduleBlock *prevBlock);

	long int LBLmax;
	ScheduleBlock *head;
	ScheduleBlock *tail;
};

DeciusMagnus
Mar 16, 2004

Seven times five
They were livin' creatures
Watch 'em come to life
Right before your eyes

Jose Cuervo posted:


code:
ScheduleBlock *b;

for (b= jobList[i]->head; b!= NULL; b= b->nextBlock)
     jobListCopy[nonEmptyMachinesCtr]->addBlock(b->jobID, b->startTime, b->processTime, b->ESTime, b->LFTime);

delete b;

Did you mean?
code:
for (b= jobList[i]->head; b!= NULL; b= b->nextBlock)
{
     jobListCopy[nonEmptyMachinesCtr]->addBlock(b->jobID, b->startTime, b->processTime, b->ESTime, b->LFTime);
     delete b;
}
This deletes the current b every iteration. Your way was deleting after the for loop was done, which means you were deleting null.

OddObserver
Apr 3, 2009

DeciusMagnus posted:

This deletes the current b every iteration. Your way was deleting after the for loop was done, which means you were deleting null.

It also accesses the nextBlock field of the just deleted one.

DeciusMagnus
Mar 16, 2004

Seven times five
They were livin' creatures
Watch 'em come to life
Right before your eyes

OddObserver posted:

It also accesses the nextBlock field of the just deleted one.

D'oh.

If there isn't a back pointer you're going to need to store both the next and the current pointer somewhere.

code:
for (b= jobList[i]->head; b!= NULL; b= b_next)
{
     jobListCopy[nonEmptyMachinesCtr]->addBlock(b->jobID, b->startTime, b->processTime, b->ESTime, b->LFTime);
     b_next = b->nextBlock;
     delete b;
}

Vanadium
Jan 8, 2005

Jose Cuervo posted:

Are you saying that the memory that was allocated to ScheduleBlock b is deallocated after the for loop is done because the pointer points to NULL, or are you saying that because it points to NULL the destructor does not get called and thus the memory being used by Is this saying that the memory allocated to ScheduleBlock b is not deallocated?

Jose Cuervo
Aug 25, 2004
Sorry, I meant to ask:

Since b is simply a pointer to objects of type ScheduleBlock, and since at the end of the for loop b points to NULL, there is nothing to deallocate?

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe
Does anyone have a good resource of how to work with strings in C? I've been programming in Java/C# for the past 4 years, and in going back to C, I've realized how spoiled I was by higher level languages. I still have my copy of K&R, and maybe I just overlooked a good section there on strings, but if someone could point it out or again, resources on the internet, that would be awesome. Thank you much!

DeciusMagnus
Mar 16, 2004

Seven times five
They were livin' creatures
Watch 'em come to life
Right before your eyes

Jose Cuervo posted:

Sorry, I meant to ask:

Since b is simply a pointer to objects of type ScheduleBlock, and since at the end of the for loop b points to NULL, there is nothing to deallocate?

At the end of the loop, there is nothing to deallocate with b. The objects you are looping through are still there.

shrughes
Oct 11, 2008

(call/cc call/cc)

pliable posted:

Does anyone have a good resource of how to work with strings in C? I've been programming in Java/C# for the past 4 years, and in going back to C, I've realized how spoiled I was by higher level languages.

Ha ha ha.

A. You should just use C++. Seriously.

B. What strings? What are you doing with them?

C. Do you want to allow NUL in your strings? (If you answered "no," pretend the answer is yes.)

The basic problem is that you have to deal with memory management and object lifetimes. The goal is to minimize the risk of memory management. How you deal with that can be.. situational. Is your program designed such that you're using a bunch of arena allocators all over the place? Good, then you'd use those somehow. Read the protip at the end. By "string manipulation" do you simply want to concatenate a bunch of strings together or build strings so that you can output them? Good, your objects' lifetimes are easy to deal with. Learn how C++'s std::vector<char> works and mimic that, and read the protip at the end. Are you going to want to tear strings apart? Learn how to use POSIX extended regular expressions, or some other C regexp library. It's uglier than using regexps in Perl but less ugly than not using regexps in C. Read the protip at the end.

Since you felt spoiled by other languages, I'm guessing the answer to all the following questions is "no":

By "string manipulation," are you not referring to manipulating "buffers" of bytes, and instead you really want O(log n) concatenation, O(1) indexing, unicode iteration, blah blah blah? Because you're writing a text editor, am I right? What OS are you using? Are you going to use any Windows APIs that want UTF-16 strings? Or do you just want to use octets and hey if somebody sends you some UTF-8, well that's cool. Or are you going to do lunatical things like capitalizing sentences written in Chinese? Do you care so much about performance that you want to pass slices within other strings, so that one object's lifetime depends on another's?



There's one universal protip: Learn how to use variable length argument lists, learn how to use vprintf or vsnprintf or what-not so that you can add string formatting to any libraries you create or use.

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

shrughes posted:

Ha ha ha.

A. You should just use C++. Seriously.

B. What strings? What are you doing with them?

C. Do you want to allow NUL in your strings? (If you answered "no," pretend the answer is yes.)

A. My systems programming class is taught in C, so no C++ for now. I'll get to C++ eventually. Hopefully :(.

B. Just in general. They just seem much harder to work with than strings in Java. There are little things here and there I don't get, like when a '\0' is automatically added to a string (I just discovered that one is automatically added when you assign a pointer a string literal).

C. ...yes (I am just following you blindly :().

To answer a few of your other random questions:

Yeah I'm referring to buffers of bytes, and again, just working with them in general. No text editor (I can't tell if this was sarcasm or not, my detector is way off)? My personal OS is OS X, but I SSH into school to program onto a server running Fedora 9. I think I'm just going to be dealing with ASCII for now, no Unicode. Performance is nice and a plus.

And I will check these out...on the whole though, thank you much for your post :)

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!
In that case, the answers to your questions in no particular order are pretty much:

1. There is no string, there is only arrays of chars.
2. Any string literal in quotes has an automatic '\0' on the end.
3. For a reference of library functions related to strings, you just need to look at what's in string.h and, from stdio.h, the printf and scanf series of functions. Those are the only ways C considers 'strings' at all, though they are still really just arrays of chars.

Vino
Aug 11, 2010
For B:

This is how C strings work. The '\0' means it's the end of the string. They are called "Null-terminated strings" and the '\0' is a null character, value of 0. So...

code:
char szString[10];
strcpy(szString, "abcdefg");
szString[3] = '\0';
printf(szString);
will get you "abc" as output. The data for "efg" remains but since the null character has been overwritten for d, C's string manipulation functions interpret that as the end of the string.

Moreover, if you do this:

code:
char szString[10];
strcpy(szString, "abcdefghijklmnopasdasdasdasd");
it'll probably crash because you'll overwrite your array of only ten characters. So with C strings you have to be careful about how much memory you have to write to the string.

If you don't like that you can use std::string or CString or other string classes that probably act more like what you're expecting. (But I guess those aren't available in C so you're boned.)

Optimus Prime Ribs
Jul 25, 2007

Vino posted:

Moreover, if you do this:

code:
char szString[10];
strcpy(szString, "abcdefghijklmnopasdasdasdasd");

Wouldn't it be better to use strcpy_s()?

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

Optimus Prime Ribs posted:

Wouldn't it be better to use strcpy_s()?

If that were a standard function and not an MS extension, sure; that being said, strncpy is a better choice than strcpy

pseudorandom name
May 6, 2007

strncpy won't NUL terminate the string if the length is greater or equal to N, and it pads out the buffer with NULs if the length is less than N.

This may make sense if you're implementing a filesystem and need to store filenames in a fixed length field, but it isn't all that useful for in-memory string manipulation.

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
If you're working in C, you have to keep track of the lengths of strings, full stop. You can keep track of lengths and use strncpy(3), or you can keep track of lengths and use memcpy(3) (the Linux kernel and glibc do this), or you can give up portability and still keep track of lengths and use strlcpy(3) with the advantage of the terminating NUL being supplied and the caveat that the result won't be NUL-padded (OpenBSD and I believe FreeBSD do this). There aren't any other options. Any other apparent options are illusory. You can do a few things to make keeping track of the lengths of strings and the amount of space allocated less painful, but you've still got to do so.

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

roomforthetuna posted:

In that case, the answers to your questions in no particular order are pretty much:

1. There is no string, there is only arrays of chars.
2. Any string literal in quotes has an automatic '\0' on the end.
3. For a reference of library functions related to strings, you just need to look at what's in string.h and, from stdio.h, the printf and scanf series of functions. Those are the only ways C considers 'strings' at all, though they are still really just arrays of chars.

1. No no, I've known this for years. C was the first language I've ever learned. I'm just coming back to it now after a long rear end hiatus.

2. I ask about this because I made a rookie mistake thinking that the compiler at runtime will automatically allocate space for a string literal, and then you can work with it...which I then learned is a big no no.

3. I'll re-read those. Maybe something isn't just clicking when working with them, and they're a lot easier than I think they are.

Vino: Knew about that stuff, one thing I was looking for was an easy way to manage them. Looks like I'm going to have to tap into my ASM knowledge and re-learn how to manually manage memory again! And yeah, I have to work with the ANSI standard C library. Can't use any other fancy libraries out there :(.

Optimus Prime Ribs
Jul 25, 2007

Otto Skorzeny posted:

If that were a standard function and not an MS extension, sure; that being said, strncpy is a better choice than strcpy

Well I guess that's why I'm not helping people in this thread. :downs:

Dooey
Jun 30, 2009
I want to have a vector of callable things, some of which are function pointers, some of which are functor objects. Is this possible?

The reason I want to do that is because I have a vector of objects and I want to return all the objects in the vector that match a certain set of properties, so I can call the function with a bunch of properties that must be matched. Is there another way to do this that I'm not realizing?

Vanadium
Jan 8, 2005

Make a vector of boost::function<your function signature> and let boost::function worry about the details. :shobon:

Freeze
Jan 2, 2006

I've never seen it written so neatly

I have to do a project where 6 threads decrement/increment a variable until it reaches 0. The first part was doing it with pthreads, which wasn't too bad, but now I need to do it again using UNIX Pipes. From what I've read, it looks like I'll need to create 12 pipes (2 for each of the threads - parent -> child and child -> parent).

The problem is, I'm more or less a complete beginner at programming in UNIX, and I can't figure out how to actually use Pipes. Can anyone help, or point to somewhere that could?

edit: Removed my idea of how to do this because I realized it was wrong

Freeze fucked around with this message at 00:59 on Oct 18, 2010

pseudorandom name
May 6, 2007

pipe(7)

I'm not sure what exactly you're doing, but guessing as to what you're assignment actually is instead of what you've described, I'd say you only need two pipes (one for orders to the threads, one for replies from the threads to the master thread).

Freeze
Jan 2, 2006

I've never seen it written so neatly

pseudorandom name posted:

pipe(7)

I'm not sure what exactly you're doing, but guessing as to what you're assignment actually is instead of what you've described, I'd say you only need two pipes (one for orders to the threads, one for replies from the threads to the master thread).

Okay so I guess I make only two pipes, and each of the six threads are created by doing a fork? Thanks for the help, I'm having a lot of trouble wrapping my mind around this for some reason.

pseudorandom name
May 6, 2007

fork creates new processes, not threads, so if your homework is specifically telling you to create threads, you should probably do that.

But my point was that you could make all the worker threads block on the command pipe and let the kernel worry about which one gets the orders when the master thread writes to that pipe.

tadashi
Feb 20, 2006

I have a C++ in Visual Studio question. I'm trying to get familiarized with Visual Studio 2010 while I also work my way through a C++ tutorial. Almost all of the C++ tutorial programs I'm creating using use:

#include <iostream>
using namespace std;

Except, when I make a new C++ console application in Visual Studio 2010, it has no idea what the gently caress to do with this header. I don't know enough about VS 2010 to figure out how to fix this. I have no problems compiling from the Visual Studio Command Prompt 2010 and this doesn't happen when I creat a C++ console application in Visual C++. Is there something I should be adding or doing differently in Visual Studio 2010? Is there something I need to add to the Source or Resource files?

I want to figure this out so I know the answer for future Visual 2010 work. If it has something to do with the fact that I'm using older C++ tutorial and something has changed in VS '10, then I'll just move on.

I have found some people asking the same question on other websites, but the answers usually involve Visual C++ and not Visual Studio 2010. Please be gentle with my baby programming bones.

tadashi fucked around with this message at 17:30 on Oct 18, 2010

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
You shouldn't have to do anything special for the iostream header to be found. Which specific project type did you select? Some of the options create projects targeting .NET's C++/CLI instead of native C++, but I'm not sure that they require anything special, either.

Adbot
ADBOT LOVES YOU

POKEMAN SAM
Jul 8, 2004

tadashi posted:

I have a C++ in Visual Studio question. I'm trying to get familiarized with Visual Studio 2010 while I also work my way through a C++ tutorial.

I started using VS2010 a few months ago, and from what I've seen there should be no discernible differences to you between VS2005 VS2008 and VS2010.

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