Segmentation fault in file I/O, cannot figure out - file-io

Basically, I have rewritten code that kept giving me a segmentation fault (core dump) error when running, and I decided to check each step to rule out issues.
My code works, until I try accessing/using the last line of the input files data. I do the same things to this line as to the line previous, but it's suggesting somethings wrong.
Here is my code for the file I/O and data handling:
The input file itself is simply:
20 20
10 10 u
5 5 d

In line 27, you dereference the uninitialised playerDirInput, which is undefined behaviour:
playerDir = (char)playerDirInput[0];
That's probably the cause of your crash. If that code block is meant to mirror the following one, it looks like you just haven't read the third item on that line, which is where playerDirInput is probably meant to come from. That would be something like:
fgets(line, 8, f);
playerRowChar = strtok(line, " ");
playerRow = atoi(playerRowChar);
playerColChar = strtok(NULL, " "); // <- fixed this, see below.
playerCol = atoi(playerColChar);
playerDirInput = strtok(NULL, " "); // <- add this.
playerDir = (char)playerDirInput[0];
However, I would suggest you instead opt for the simpler sscanf version, which would go something like (including a check to ensure you get the three items):
fgets(line, 8, f);
if (sscanf(line, "%d %d %c", &playerRow, &playerCol, &playerDir) != 3) {
handleErrorIntelligently();
}
I tend to prefer fgets followed by sscanf, rather than fscanf. The latter can fail in such a way that you're not sure where the input stream pointer ends up as. With fgets, you always know you've read a line (or can easily detect that you read a partial line and adjust for it).
Other potential problems you should look at:
On line 25, this strtok should be of the NULL type, not line. The latter will simply re-read the first item on that line wheras you want the next item.
You really should check functions that can return problematic values (such as NULL from strtok). Otherwise, using them can cause issues. That depends on the data you're reading, of course, so may not necessarily be a problem if you control that.

Related

Why do I get “Lexical with name '$x' does not exist in this frame” when using “will leave”?

I have the following Raku code:
class Thing {
method close {
say "closed";
}
};
for 1..1000 {
my $x will leave { .close } = Thing.new;
}
Running it, I get the error:
Lexical with name '$x' does not exist in this frame
in block <unit> at c.raku line 7
Interestingly, this only happens if the number of iterations is high enough (with 500 or 100, I do not get any error messages).
If I change the body of the cycle to
my $x = Thing.new;
LEAVE $x.close;
then everything works without errors as well.
What is happening here? Did I misunderstand the will leave construct? (It seems to me the two versions should be equivalent.)
EDIT: Further observation – when running the code multiple times, the error appears nondeterministically. This suggests that the problem is somehow connected to garbage collection, but I am still confused as to what actually happens here.
I am using Rakudo v2021.03.
This is a bug. Have made an issue for it: https://github.com/rakudo/rakudo/issues/4403
I suggest using the workaround in the meantime.

Does Objective-C run code line by line?

I'm really new to programming Objective-C and programming in general, so forgive me if this is a super obvious question:
I'm wondering if Objective-C runs code line by line. What I mean by that is if it processes one line before moving onto another, or if it just runs the next line regardless of whether the previous line is finished or not.
For example,
int difference = number1 - number2;
if (difference < 0) {
difference = difference + 10;
}
result = difference;
Say that number1 = 3 and number2 = 7. When I run this code, will it go line by line and run the if block before line 5 and give me result = 6, or will it start running the if block and line 5 at the same time and give me result = -4?
Thanks in advance!
EDIT: Changed modulo to addition because of Obj-C quirk.
As far as your thinking goes you may as well assume that it runs line by line.
In fact the compiler may put the code into a more efficient order (i.e. making sure that divisions aren't too close together, as this could make things slow). However even when the compiler does re-order things it makes sure that a result is calculated before it is needed. When you build the code in a fully optimised fashion (release mode) if you debug it you can see that the code has actually been re-ordered (the debugger jumps when you wouldn't expect it to). However as far as thinking about your code goes it's safe to assume that it runs it in the order you write it.
If you are new to programming, all programming languages you will meet at the beginning of your learning will execute statements sequentially. It means that the next one happens only after the previous one ends. However, languages like Objective C are not line-oriented and what matters are not lines but statements, like assignment ending with semicolon! or if statement.

Variable sized arrays in Objective-C?

Okay, so apparently this works:
void foo(size_t s) {
int myArray[s];
// ... use myArray...
}
Is this really legal? I mean, it must be, because it compiles (where the C compiler would reject it as non-constant). The first part of my question is: how does this work? I assume it's allocating it on the stack? Is this different from using alloca()?
Practically, I found some code that does this:
void bar(size_t chunkSize) {
CFReadStreamRef foo = NULL;
// ...some stuff to init foo...
while (stuffToDo) {
UInt8 buffer[chunkSize];
// ...read some data from stream into buffer
// using CFReadStreamRead()...
}
}
This works. However, when I move the buffer allocation from inside the loop to the first line of the function (directly before foo is declared), the function... stops working. In the debugger it gets to the first access of local variables and then just... exits. I don't see any exceptions being thrown, it doesn't crash, it just program carries on running (in reality the function returns a string and that return value is NULL, which is what the return variable is initialized to). I'm not sure what's going on. The second part of my questions is, in light of the first part, what the heck is going on?
it is legal in C99, although dangerous, and yes -- it is like alloca.
because it's like alloca, you want reasonably sized arrays when allocating on the stack. i am not sure if this is defined if the length is zero, but you could definitely cause a stack overflow if the array is 'large enough' to do so.
as far as what is going on -- pulling it out of the loop should make no difference if the sizes are reasonable. i suspect you are seeing undefined behavior because a parameter value is too large (or perhaps 0) -- you should validate the chunkSize parameter. the assembly will tell you why pulling it out of the loop makes a difference (assuming everything else in the program is well-formed).

File Input output in Mathematica

I am writing test-cases for a problem,I want to check my test-cases with Mathematica but I am facing some problems with file input/output.
I have to take Input from a file say "Test.in",the date consists of an Integer/String in each line and the input is terminated by EOF,I have to take the input (every line,one at a time) and in each step I have to process the input and output to a file say "output.out".How can we do this in Mathematica?
PS:I am using Mathematica 7.0
ADDED:
A sample of Test.in would be like this.
You asked to read (every line,one at a time). Well, that is surely not the Mathematica way of doing things, but as you asked for it, try something along the lines of:
strInp = OpenRead ["Test.in"];
strOut = OpenWrite ["Test.out"];
While[(str=Read[strInp, Number) != EndOfFile,
out = yourprocess[str];
Write [strOut,out];
];
Close [strOut];
Close [strInp];
(* Now show the output file *)
FilePrint ["Test.out]
Edit Other answers posted better and more Mathematica-ish ways of doing this, but that generally implies NOT reading one at a time, as Mathematica favors functional, list-wide programming rather than the iterative way.
It's rather clunky to read each value one at a time, but it's natural in M- to read them all at once and then process each one.
Here's a simple infrastructure I use all the time:
(* step one: get data *)
data = Import["ideone_fM0rs.txt", "Lines"];
(* step two: ??? *)
res = {};
Module[{value, result},
value = #;
result = yourCodeHere[value];
AppendTo[res, result];
]& /# data;
(* step three: PROFIT! *)
Export["out.txt", res, "Lines"];
but see Jon McLoone on AppendTo vs Sow/Reap for large data sets: http://blog.wolfram.com/2011/12/07/10-tips-for-writing-fast-mathematica-code.
Here's a variation with Sow/Reap for the times you'd like to collect values under various tags or categories or genuses or whatever:
data = Import["ideone_fM0rs.txt", "Lines"];
res = Reap[Module[{value, result, tag},
value = #;
result = yourCodeHere[value];
tag = generateTag[value]
Sow[result, tag];
]& /# data, _, Rule][[2]];
Export["out.txt", res, "Lines"];
It's tempting to roll all that up into a single awe-inspiring one-liner, but for maintainability I like to keep it unrolled with each step made explicit.
Of course, yourCodeHere[value] could instead be many lines of well-commented code.
Note: I downloaded your data to a local file ideone_fM0rs.txt using the download link at http://ideone.com/fM0rs
That's straightforward to do, and like everything in Mathematica there is more than one way to do it. Personally, I'd use
data = ReadList["Test.in", Number, RecordLists-> True];
and then process data using Map. There's also Import and your data probably is best loaded as type Table, although you can check the full list and see what's there. You could also use Read, but you'd have to control the file open/close yourself.
For the input aspect, this might give you a start.
vals = Import["http://ideone.com/fM0rs",
"Table"] /. {aa_ /; ! NumberQ[aa] && FreeQ[aa, List], ___} :>
Sequence[] /. {} :> Sequence[]
I think others on this forum may have better ways to go about it though; I'm not much versed in the Import/Export realm.
Daniel Lichtblau
Wolfram Research

sprintf fails spontaneously depending on what printf and NSLog calls there are

Hello I have a bizarre problem with sprintf. Here's my code:
void draw_number(int number,int height,int xpos,int ypos){
char string_buffer[5]; //5000 is the maximum score, hence 4 characters plus null character equals 5
printf("Number - %i\n",number);
sprintf(string_buffer,"%i",number); //Get string
printf("String - %s\n",string_buffer);
int y_down = ypos + height;
for (int x = 0; x < 5; x++) {
char character = string_buffer[x];
if(character == NULL){ //Blank characters occur at the end of the number from spintf. Testing with NULL works
break;
}
int x_left = xpos+height*x;
int x_right = x_left+height;
GLfloat vertices[] = {x_left,ypos,x_right,ypos,x_left,y_down,x_right,y_down};
rectangle2d(vertices, number_textures[atoi(strcat(&character,"\0"))], full_texture_texcoords);
}
}
With the printf calls there, the numbers are printed successfully and the numbers are drawn as expected. When I take them away, I can't view the output and compare it, of-course, but the numbers aren't rendering correctly. I assume sprintf breaks somehow.
This also happens with NSLog. Adding NSLog's anywhere in the program can either break or fix the function.
What on earth is going on?
This is using Objective-C with the iOS 4 SDK.
Thank you for any answer.
Well this bit of code is definately odd
char character = string_buffer[x];
...
... strcat(&character,"\0") ...
Originally I was thinking that depending on when there happens to be a NUL terminator on the stack this will clober some peice of memory, and could be causing your problems. However, since you're appending the empty string I don't think it will have any effect.
Perhaps the contents of the stack actually contain numbers that atoi is interpretting?Either way I suggest you fix that and see if it solves your issue.
As to how to fix it Georg Fritzsche beat me to it.
With strcat(&character,"\0") you are trying to use a single character as a character array. This will probably result in atoi() returning completely different values from what you're expecting (as you have no null-termination) or simply crash.
To fix the original approach, you could use proper a zero-terminated string:
char number[] = { string_buffer[x], '\0' };
// ...
... number_textures[atoi(number)] ...
But even easier would be to simply use the following:
... number_textures[character - '0'] ...
Don't use NULL to compare against a character, use '\0' since it's a character you're looking for. Also, your code comment sounds surprised, of course a '\0' will occur at the end of the string, that is how C terminates strings.
If your number is ever larger than 9999, you will have a buffer overflow which can cause unpredicable effects.
When you have that kind of problem, instantly think stack or heap corruption. You should dynamically allocate your buffer with enough size- having it as a fixed size is BEGGING for this kind of trouble. Because you don't check that the number is within the max- if you ever had another bug that caused it to be above the max, you'd get this problem here.