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
mistermojo
Jul 3, 2004

ok, I might be stupid and not understanding anything, but here's a problem I'm having:

This code reads in a file line by line, adding each element to a linked list (separated by commas). It works perfectly for the first line, but seg faults right after it exits the while loop.

Here's the code:

code:
if (mainfile != 0){
		char line[128];
		for (i = 0; i < elementnumber; i++){
			fgets (line, sizeof line, mainfile);
			char *pch;
			int temp;
			array[i] = new Node();
			start = array[i];
			pch = strtok (line, ",");
			temp = atoi(pch);
			array[i]->vertex = temp;
			array[i]->next = new Node();
			array[i] = array[i]->next;
			while (pch != NULL){
				pch = strtok(NULL, ",");
				temp = atoi(pch);
				array[i]->vertex = temp;
				array[i]->next = new Node();
				array[i] = array[i]->next;
			}
			array[i] = start;
		}
	}

Adbot
ADBOT LOVES YOU

Paniolo
Oct 9, 2007

Heads will roll.
Strtok() returns null when there aren't any tokens left, but you aren't checking the return value before passing it as a parameter to atoi(). This is probably what you wanted:

code:
pch = strtok(line, ",");
while (pch) {
   // loop body
   pch = strtok(NULL, ",");
}

Paniolo fucked around with this message at 07:22 on Dec 7, 2009

CliffyBMine!
Oct 2, 2006

Epic Megagames? I'm Epic MegaGAY!
I've got a interview with Microsoft this week and I've been brushing up my C skills but I ran into a problem when trying to reverse the order of the words in a string ("hello friend" becomes "ollef dneirf").

code:
void reverseOrderWords(char* string)
{
	int len = strlen(string);
	int i, j;
	int start = 0;
	int end = 0;
	for (i = 0; i < len; i++)
	{
		printf("test\n");
		if ((string[i] == ' ') || (i == len - 1))
		{
			if((i == len - 1) && (string[i] != ' '))
				end = i;
			else
				end = i - 1;
				
			for(j = 0; j < (end-start)/2; j++)
			{
				printf("test2\n");
				char temp = string[start + j];
				printf("test3\n");
				string[start + j] = string[end - j];
				printf("test4\n");
				string[end-j] = temp;
				printf("test5\n");
			}
			start = i + 1;
			end = i + 1;
		}
		else
		{
			end++;
		}
	}
	puts(string);
}
code:
string[start + j] = string[end - j];
This is what throws the segmentation fault... Strings are character arrays in C so shouldn't this be valid code?

The code works in C# (with a StringBuilder object b/c String objects are immutable) so I know the logic of it is sound.

Any idea?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

CliffyBMine! posted:

Any idea?

Stop trying to write to a string-literal. (Also that code is a huge mess organizationally.)

shrughes
Oct 11, 2008

(call/cc call/cc)

CliffyBMine! posted:

:words

See http://csharppad.org/ViewPaste/WWAhztYz6EKgRMHMFWOS4A

I converted your code to .NET code and its output is broken. "dnierf" isn't the backwards of "friend".

CliffyBMine!
Oct 2, 2006

Epic Megagames? I'm Epic MegaGAY!

Avenging Dentist posted:

Stop trying to write to a string-literal. (Also that code is a huge mess organizationally.)

This is my second try, I wanted to see if I could do it in-place this time. Is it possible?

edit:

shrughes posted:

See http://csharppad.org/ViewPaste/WWAhztYz6EKgRMHMFWOS4A

I converted your code to .NET code and its output is broken. "dnierf" isn't the backwards of "friend".

That's weird, the output of my C# code is "olleh dneirf".

CliffyBMine! fucked around with this message at 07:49 on Dec 8, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

CliffyBMine! posted:

This is my second try, I wanted to see if I could do it in-place this time. Is it possible?

Of course it is, and it's possible to make it a lot easier to read.

Gumbercules
Jan 12, 2004

These aren't my lamps. These have feet.

CliffyBMine! posted:

Any idea?

First of all, the most important thing is to be able to describe your thought process while writing the algorithm. Judging from the poor way you presented your code here (debug flags still intact, no comments), you should probably work on that.

Secondly, you're probably calling your function like reverseOrderOfString("A string") - that dog won't hunt in C. Rather than modifying the string in place, your function should allocate a new string, copy it from the input string (do the word-reversal during the copy), and then return the new string - much better function.

Thirdly, just answer your interview questions in C# if you're more comfortable with it - in my experience most interviewers will allow you to choose the language, they're really only interested in your thought process and problem-solving ability.

Good luck.

Edit: Yes, you can do an in-place version, but you'll get segmentation faults if you try to modify a string literal. AD already pointed out that the organization could be better.

Gumbercules fucked around with this message at 07:52 on Dec 8, 2009

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Gumbercules posted:

First of all, the most important thing is to be able to describe your thought process while writing the algorithm. Judging from the poor way you presented your code here (debug flags still intact, no comments), you should probably work on that.

On this note, changing "hello friend" to "olleh dneirf" is not "reversing the order of the words in a string", it is "reversing the order of the letters in each word", and any interviewer for a programming position worth their salt will see huge warning lights if you can't describe problem statements clearly and correctly.

Remember: It'll probably be assumed that as long as you can communicate well and program in some language, you can be trained to use any normal programming environment, language, and libraries that the job needs you to use. You don't need to show off your ability to do specifics like work in-place in C unless they specifically ask for that - you need to demonstrate that you can do problem-solving in general.

CliffyBMine!
Oct 2, 2006

Epic Megagames? I'm Epic MegaGAY!

Gumbercules posted:

First of all, the most important thing is to be able to describe your thought process while writing the algorithm. Judging from the poor way you presented your code here (debug flags still intact, no comments), you should probably work on that.

Secondly, you're probably calling your function like reverseOrderOfString("A string") - that dog won't hunt in C. Rather than modifying the string in place, your function should allocate a new string, copy it from the input string (do the word-reversal during the copy), and then return the new string - much better function.

Thirdly, just answer your interview questions in C# if you're more comfortable with it - in my experience most interviewers will allow you to choose the language, they're really only interested in your thought process and problem-solving ability.

Good luck.

Edit: Yes, you can do an in-place version, but you'll get segmentation faults if you try to modify a string literal. AD already pointed out that the organization could be better.

Good to know, the college recruiter I was assigned to only mentioned C and C++ so I assumed it was required.

Thanks for the advice by the way!

ShoulderDaemon posted:

On this note, changing "hello friend" to "olleh dneirf" is not "reversing the order of the words in a string", it is "reversing the order of the letters in each word", and any interviewer for a programming position worth their salt will see huge warning lights if you can't describe problem statements clearly and correctly.

Remember: It'll probably be assumed that as long as you can communicate well and program in some language, you can be trained to use any normal programming environment, language, and libraries that the job needs you to use. You don't need to show off your ability to do specifics like work in-place in C unless they specifically ask for that - you need to demonstrate that you can do problem-solving in general.

Yeah that's what I meant, sorry :)

I'll try to work on code presentation next.

Thanks for the advice guys, it helps a lot.

FastEddie
Oct 4, 2003

CliffyBMine! posted:


code:
void reverse_string(char *sz) {
  char *e;
  if (!sz[0]) return;
  for (e = sz; e[1]; ++e);
  for (; sz < e; ++sz, --e) {
    char t = *e;
    *e = *sz;
    *sz = t;
  }
}
And here's a test:
code:
#include <stdio.h>
#include <string.h>

int errors = 0;

void test(const char *in, const char *expected) {
  char *in_copy = strdup(in);
  reverse_string(in_copy);
  if (strcmp(expected, in_copy)) {
    printf("FAIL - expected %s, got %s\n", expected, in_copy);
    ++errors;
  }
  free(in_copy);
}

int main() {
  test("", "");
  test("a", "a");
  test("abc", "cba");
  test("Hello,  World  !", "!  dlroW  ,olleH");
  if (!errors) puts("PASS");
  return errors;
}

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

FastEddie posted:

:words:

I hereby present FastEddie the Cavern of COBOL FizzBuzz Award for correctly solving the wrong problem!!!

Captain Lou
Jun 18, 2004

buenas tardes amigo
code:
>>> ' '.join([e[::-1] for e in 'hello friend'.split()])
'olleh dneirf'
Python superiority

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
print reverse.' 'for split/ /,'hello friend'



Grats on writing python with more punctuation than perl, somehow

That Turkey Story
Mar 30, 2003

Captain Lou posted:

:-1]

shrughes
Oct 11, 2008

(call/cc call/cc)

FastEddie posted:

And here's a test:

FAIL - expected 六, got ���

test("六", "六");

FastEddie
Oct 4, 2003

Avenging Dentist posted:

I hereby present FastEddie the Cavern of COBOL FizzBuzz Award for correctly solving the wrong problem!!!
Not if you put "olleh dneirf" into it. He wants to reverse the words in a sentence, no? And he's already reversed each word.

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

FastEddie posted:

Not if you put "olleh dneirf" into it. He wants to reverse the words in a sentence, no? And he's already reversed each word.

ShoulderDaemon posted:

On this note, changing "hello friend" to "olleh dneirf" is not "reversing the order of the words in a string", it is "reversing the order of the letters in each word", and any interviewer for a programming position worth their salt will see huge warning lights if you can't describe problem statements clearly and correctly.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

FastEddie posted:

Not if you put "olleh dneirf" into it. He wants to reverse the words in a sentence, no? And he's already reversed each word.

Yes, that is clearly what he meant and you're clearly not just backpedaling in an attempt to save face.

FastEddie
Oct 4, 2003

Avenging Dentist posted:

Yes, that is clearly what he meant and you're clearly not just backpedaling in an attempt to save face.
Why would he want to reverse the characters in each word? That's the stupidest interview question I've ever heard of!

CliffyBMine!
Oct 2, 2006

Epic Megagames? I'm Epic MegaGAY!

FastEddie posted:

Why would he want to reverse the characters in each word? That's the stupidest interview question I've ever heard of!

I'll be sure to mention this to the interviewer if the question comes up.

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL

shrughes posted:

FAIL - expected 六, got ���

test("六", "六");

maybe im missing something here but surely any function that manipulates words and letters is gonna choke if you call it with a picture?

pseudorandom name
May 6, 2007

Nigglypuff posted:

maybe im missing something here but surely any function that manipulates words and letters is gonna choke if you call it with a picture?

Yes, you're missing something.

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

but aren't English words just pictures of letters? :2bong:

mellifluous
Jun 28, 2007
On a C++ test I took there was the question "Why did Stroustrup apologize for auto_ptr?". It was a piece of information that I missed. Can anyone explain?

irishcoffee
Sep 16, 2008
I have a function definition as follows:

void foo(void *arr, size_t num_elem, size_t elem_size)

Arr can point to any array of strings, ints, longs, floats, whatever.

I'm having trouble referencing this array and preforming things such as memcpy, or just referencing this array at all. I know I need to use casting and pointer arithmetic, and I don't have trouble if I know the array is full of ints or floats, but strings/chars are confusing me.

How would I go about memcpying this array regardless of type, and referencing its elements, regardless of type.

Yes this is school related, but I've been messing with this for a while now, and this is just a very small part of a very large program. Any tips would be appreciated.

newsomnuke
Feb 25, 2007

It's not a good idea to memcpy non-POD types (ie classes like string) because they may have dynamically allocated members.

To reference its elements you need to know what type it is. Just size alone won't work. Either pass in some identifier which specifies this and cast it, or (better) use templates.

Vanadium
Jan 8, 2005

You cannot tell whether you want to copy the data in the array or whether you need to interpret the array as pointers to follow, so there is nothing you can do.

What do you mean by referencing the elements? Without knowing what type they are, that does not really buy you anything.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

mellifluous posted:

On a C++ test I took there was the question "Why did Stroustrup apologize for auto_ptr?". It was a piece of information that I missed. Can anyone explain?

Because it was a terrible, lazy conflagration of the proposed safe_ptr and counted_ptr (now unique_ptr and shared_ptr in C++0x).

FastEddie
Oct 4, 2003

irishcoffee posted:

I have a function definition as follows:

void foo(void *arr, size_t num_elem, size_t elem_size)

Arr can point to any array of strings, ints, longs, floats, whatever.

How would I go about memcpying this array regardless of type
code:
void *destination = ...
memcpy(destination, arr, num_elem * elem_size);

quote:

and referencing its elements, regardless of type.
code:
void *elem = (char*)arr + (index * elem_size);
You'll need another cast if you're using C++.

FastEddie fucked around with this message at 21:01 on Dec 9, 2009

RussianManiac
Dec 27, 2005

by Ozmaugh
Can somebody explain how using references instead of pointers when recording children for a tree can save on space and provide a short coding example?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

RussianManiac posted:

Can somebody explain how using references instead of pointers when recording children for a tree can save on space and provide a short coding example?

No because that makes no sense. Basically every real compiler implements references as const pointers, more or less (note: not pointers to const).

RussianManiac
Dec 27, 2005

by Ozmaugh

Avenging Dentist posted:

No because that makes no sense. Basically every real compiler implements references as const pointers, more or less (note: not pointers to const).

I was told that some compilers might do optimizations and use less than word size if reference is used versus pointer. Are there situations where this is possible?

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

RussianManiac posted:

I was told that some compilers might do optimizations and use less than word size if reference is used versus pointer. Are there situations where this is possible?

I guess on architectures where near and far pointers are different sizes, the compiler might be able to statically verify that certain references only need the storage allocated for a near pointer?

I mean, theoretically, it's possible for a compiler to prove in some cases that all accesses of some object are through a pointer in a parent object, and just inline the child into the parent, but that involves potentially special-casing functions that access the parent, and it raises all sorts of complications with sizeof, aliasing, pointer arithmetic... I don't think any halfway sane C compiler would ever try to go down that road.

RussianManiac
Dec 27, 2005

by Ozmaugh

ShoulderDaemon posted:

I guess on architectures where near and far pointers are different sizes, the compiler might be able to statically verify that certain references only need the storage allocated for a near pointer?

I mean, theoretically, it's possible for a compiler to prove in some cases that all accesses of some object are through a pointer in a parent object, and just inline the child into the parent, but that involves potentially special-casing functions that access the parent, and it raises all sorts of complications with sizeof, aliasing, pointer arithmetic... I don't think any halfway sane C compiler would ever try to go down that road.

My CS professor mentioned this the other day when I was talking about my SuffixTree implementation and saving on memory. I guess he must have been tripping, or I just misunderstood him?

RussianManiac fucked around with this message at 00:05 on Dec 10, 2009

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

RussianManiac posted:

My CS professor mentioned this the other day when I was talking about my SuffixTree implementation and saving on memory. I guess he must have been tripping?

For structures like trees where you frequently know an upper bound on the space requirements in advance, a common tactic is to allocate an array of nodes instead of individual nodes, and store offsets into the array instead of pointers. If you know you'll never need a tree with more than 216 nodes, for example, you can then use a smaller space to store the index than you could store the pointer in. Are you sure this isn't what he was talking about?

Or, depending on your structure, you can make the pointers completely implicit in the ordering of the nodes in the array, as is commonly done with balanced binary trees.

RussianManiac
Dec 27, 2005

by Ozmaugh

ShoulderDaemon posted:

For structures like trees where you frequently know an upper bound on the space requirements in advance, a common tactic is to allocate an array of nodes instead of individual nodes, and store offsets into the array instead of pointers. If you know you'll never need a tree with more than 216 nodes, for example, you can then use a smaller space to store the index than you could store the pointer in. Are you sure this isn't what he was talking about?

Or, depending on your structure, you can make the pointers completely implicit in the ordering of the nodes in the array, as is commonly done with balanced binary trees.

Oh, it might have been. Makes sense. Thanks! I think in my case the number of nodes shouldn't be getting bigger than 2^32, so I could save some space this way on 64 bit machine right? But if my number of nodes is larger than 2^32 then there is no point in doing this? Is there a way to store an integer using 5 or 6 bytes that would also be efficient?

OddObserver
Apr 3, 2009
Using reference for trees would also be rather annoying, considering you can't just set them to null...

Screeb
Dec 28, 2004

status: jiggled
I need to create a shitload (dozens of millions) of objects and store them in an std::vector. Currently I'm doing a loop for the number of objects I need to create, and new-ing them one by one and shoving them into the vector. The objects are all the same type and use the default constructor with no parameters (ie vec[i] = new foo();) The problem of course, is that's slow as gently caress, and ends up taking almost twice as much memory as it should, due to fragmentation. Is there any black magic I can do to solve this? Note also that doing a single big allocation is not good either, since it's gigs of memory. Ideally I would like to solve both the speed issue and the memory usage issue, but the most important is the memory issue.

Adbot
ADBOT LOVES YOU

Vanadium
Jan 8, 2005

I do not have any black magic to offer, so chances are you thought of this and it just does not work for your, but maybe you could use a deque<foo> instead of a vector<foo*> so you do not have to allocate pointers to your objects. The deque makes it not-necessarily-contiguous, so presumably it will be doing a few smaller allocations rather than a single big one, too.

Otherwise you could manually allocate chunks of memory, like new foo[1024]; and then have the elements of your vector point inside those arrays. The downside is that you would have to track the lifetime of the chunks separately, I suppose, but it would let you work around the fragmentation issue. A fancier approach to this is making the vector use a custom allocator that does something similar, but I have no idea how much that buys you.

Presumably you cannot get around having to call the default constructor for each object, but maybe allocating raw memory (ie, char[n]) and just memsetting it to zero is appropriate and faster for your objects.

There is a bunch of stuff you can do with choosing another data structures, I suppose, but I have no idea what your requirements are beyond storing a huge amount of objects somewhere. :shobon:

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