Comment on: [Why does my code work] I have created a parser in C and if I do not allocate and immediately free an array it breaks.
0 17 Jun 2016 00:03 u/tame in v/programmingComment on: [Why does my code work] I have created a parser in C and if I do not allocate and immediately free an array it breaks.
Sure. :) First up, I'm a bit of a dinosaur in terms of embedded systems and so what I'm saying applies to old, tiny micros. Even on a modern 'small' chip like an AVR or similar you can probably get away with treating it like a little desktop computer. That said...
Generally in embedded software development, static memory allocation is favoured over dynamic allocation. Embedded systems often have very limited processing power and memory, and are expected to run reliably for long periods of time. They're also sometimes hard to debug due to the difficulty of getting reliable debug information out of them.
Static allocation is simpler, eliminates memory leaks and a whole bunch of other potential pointer issues, and generally is a better option in embedded development.
In this case you could do something like this (whoops, I was just going to write some pseudocode... :P )
// Parses an integer, terminated by a US character, from 'str' starting at the
// given position. Updates the position if found, otherwise returns false.
bool parseInt(char *str, int& pos, int& val) {
int end = pos;
// Find the first non-numeric character
while ('0' <= str[end] && str[end] <= '9')
end++;
// If the next char isn't an US, then fail
if (str[end] != US)
return false;
// Parse the value
str[end] = 0;
val = atoi(str+pos);
str[end] = US; // NOTE: Don't need this if we don't use the string again
pos = end+1;
return true;
}
bool parseDispenseRequest(char *input, int& position, int& currency, int& amount) {
int curpos = 0;
return parseInt(input, curpos, position)
&& parseInt(input, curpos, currency)
&& parseInt(input, curpos, amount)
&& (input[curpos] == RS);
}
Comment on: [Why does my code work] I have created a parser in C and if I do not allocate and immediately free an array it breaks.
The first thing to look for when you get this kind of "I change some random other thing and it starts/stops working" behaviour is some kind of memory corruption. Check the limits on all your loops, double check memory allocation/deallocation (if you're using it, which on a microcontroller you probably don't want to), make sure every pointer is initialized properly. Chances are, your allocating and freeing the array changes the layout of the rest of your data in memory in just the right way so that whatever bad memory access is happening now happens to some less important memory.
Onto the code... You probably want to change allocCharBuffer() so that it allocates and initializes (numberOfChars+1) bytes, not (numberOfChars) bytes, to make room for the terminating NUL character at the end of the string. My guess is your code is crashing when you call atoi() on an unterminated string.
When you allocate your string, this causes your next allocCharBuffer() to land in some other chunk of memory which, chances are, is already initialized with zeroes, which is why it works in this case (for a while).
Comment on: Why can't programmers... Program?
On a similar theme I've been hearing a lot recently about aphantasia - as a very visual person I find this incomprehensible but a few of my friends swear that this is how they experience the world.
Comment on: Why can't programmers... Program?
Logic flow may be binary but there are many cases where the best way to solve a problem uses a continuous algorithm rather than a discrete one. Any time you're trying to figure out "how much" instead of just "whether or not", things get a lot more interesting. (A topical example would be driverless cars - you don't want the car to be doing "if (x) turnLeft(); else if (y) turnRight();", you want it to be doing "adjustWheel(calculateBestSteeringDelta(inputs));"
Comment on: Why can't programmers... Program?
Yeah, I thought the same as I was reading the retraction. You'll note he doesn't actually say anything about why the original paper's conclusions were wrong. It's a partial retraction (his words) in the face of social opposition.
Comment on: Why can't programmers... Program?
I find it fascinating that, no matter how much people are now insisting that the camel doesn't have two humps, I have never met anyone who's taught programming beyond the very basics who believes that "anyone can program". I've tutored Java at a tertiary level and there are some people, otherwise quite intelligent, who simply do not have the mental machinery required.
Comment on: I hate my job as a web developer because there is zero creative thought. In what industry would I have the most creative freedom while programming?
Basically this. Junior programming jobs don't have much creative scope. The exception is if you work in a really small company, because you're more likely to work on one-person projects.
Comment on: I hate my job as a web developer because there is zero creative thought. In what industry would I have the most creative freedom while programming?
The creative stuff you enjoy would fall more under 'business analysis' and 'software engineering' than 'programming'.
Comment on: F*** You, I Quit - Hiring Is Broken
If I'm hiring a software dev specifically and solely for the rote UI work then sure. But if I'm not some accounting software company that survives by grunting out yet another quarterly revision of the same mediocre software package, then I want someone who can do more than just the grunt work, I want a team member who can analyze new problems and create new algorithms to solve them. And to test this skill, it's actually better to give them a problem to solve that they don't already know off the top of their head.
Comment on: F*** You, I Quit - Hiring Is Broken
I disagree with it. If they can't write a BFS or DFS on the spot, from first principles, then I don't want to hire them. Sure, maybe when they have access to stackoverflow.com they are capable of cut-n-pasting their way through most business application development jobs, but I want someone who can solve new problems which don't have example code available.
Comment on: How to Detect Faces With the Google Cloud Vision API
Do you want a panopticon? Because that's how you get a panopticon.
I don't understand how "any device with a camera could be streaming video to a third party server somewhere on the internet at any time" doesn't horrify people. It's like those goddamn Barbie dolls which are always streaming audio back to the mothership.
Comment on: [CS Theory Stack Exchange] If God had a book of algorithms, which would be included?
Evolutionary algorithms, of course.
Comment on: Is being a video game programmer as bad as everyone says it is?
It depends hugely on who you work for, but generally it's high pressure and low pay compared with other commercial software development. You're solving much harder problems than your standard business application, and more of them, with less budget (in both time and money) to do it in. Your game is probably at the mercy of studio or VC funding and could get cancelled at any time (and your job along with it). And there's always an army of university grads willing to do your job for peanuts just so they can work in the game industry.
On the plus side, company culture is usually fun (obviously varies) and you learn a lot.
If you're going to be a professional game developer, do it before you have kids.
Comment on: What is the best language for someone who wants to learn to code for the first time?
Depends what you mean by "good language". PHP is great for just slapping something together - I use it over perl for command line scripts for text parsing and stuff.
Comment on: What is the best language for someone who wants to learn to code for the first time?
Meh, Basic is weakly typed (or at least some versions are) and plenty of people started with it. JS is probably no worse in that regard.
Comment on: Got a game for you low-level programming NERDS
Zachtronics games are awesome. I haven't played this one yet but as I understand it, the language in TIS-100 is a pretty typical assembler language for a micro. (For bonus points, this guy wrote a TIS-100 emulator for executing game code outside of the game. :)
Comment on: What were your first projects, and what were some important things you learned from them?
When I first started teaching myself to program?
- Various fractal image renders = pixel graphics, mouse/keyboard input, window management
- Various small games (Tetris etc.) = 'Realtime' programming, animation, bitmap graphics, storing game state
- Programming text editor with syntax highlighting and automatic indenting = Document/View architecture (ie. MVC design pattern, although I ballsed it up and put all my 'model' code in the view... you learn by making mistakes :P ), text handling, caching
- Various raytracer type things = implicit rendering, vectors, matrices, coordinate transformations, lighting, procedural texturing, text file parsing
- More games = networking, latency / desynch / resynchronization, in-game chat
That kind of thing. :)
Comment on: Looking for a text editor or IDE
I haven't used it since VS2008, but it was pretty damn good back then. As one of the few Microsoft products that's extensively used by the team that develops it, it's thoroughly dogfooded and (IMO) one of their best products.
Comment on: Looking for a text editor or IDE
I've been using CodeLite for the past few years, and I've generally been pretty happy with it. It takes a little while to parse and tag source but after that it's fairly quick, and it's got good code navigation and alright code completion. Git and SVN integration built in along with a bunch of other nice things like CppCheck, UnitTest++, wxCrafter etc.
Still interested to see what other suggestions you turn up.
Comment on: Looking for a text editor or IDE
He's gonna say Visual Studio. :P
Comment on: Does the Go programming language have any future?
Asynchronous is anything that happens 'in the background' from the point of view of the caller, no matter how it's implemented. Multi-threading, cooperative multitasking, dedicated external hardware (eg. DMA) are all asynchronous.
Comment on: Does the Go programming language have any future?
The web startup geeks over at Hacker News love that kind of stuff, I think it might be trendy at the moment or something.
Comment on: A little script I wrote to find links for voat
That's pretty cool. Nice work!
Comment on: A little script I wrote to find links for voat
Now filter out already posted links, then rank them according to some heuristic, then post the top few automatically. Yay, voatbot!
Comment on: Learn C++ in Less than 4 Hours | Intro Lectures for Beginners
Titles like this only serve to mislead non-technical people about how much effort is actually required to learn to program.
Instead, I suggest Teach Yourself Programming In 10 Years.
Comment on: Another bigot joining Github. Inclusiveness doesn't include white men.
Dunno about the thumbnail above but I sure as hell wouldn't feel safe hosting a project on github any more.
Comment on: Hate GitHub being taken over by gender politics? Don't worry, you're not alone.
Interest. It says so in the caption. /s
Comment on: I did my very first code and I feel quite accomplished. Any tips for keep on going?
Don't stop.
Comment on: Programmer quits work on project after getting triggered by a variable name (The comments, however . . .)
While I think that the article author and the project lead come across as total knobs here, in all fairness the guy quit the project after having a whole bunch of his permissions revoked with no warning. It's not just "guy starts making whiny SJW noises then quits." It's "guy starts making whiny SJW noises and gets instantly banned by project owner with no discussion." He then quit the community in response.
No matter how annoying you find the whiny SJW noises, banning someone outright with no discussion based on a difference of opinion is poor form.
Comment on: Apollo 11 source code
Is there a way that this could be read that changes the meaning? I'd assumed they were checksums or error handling of some sort.
Comment on: How Microsoft Lost the API War - Joel on Software
True about the old bugs equals malware thing. I think the current approach is arguably optimal: With each new revision of the software, provide a sandboxed, virtualised version of the old version for compatibility. If I understand right, the "compatibility mode" in every Windows since 7 is literally a mini-VM running an older Windows runtime. This gets all the hacky workarounds out of the current-generation code while perfectly preserving the old execution environment.
Comment on: How Microsoft Lost the API War - Joel on Software
I've just started Android development and already I'm getting pissed off by the number of things that are introduced and then deprecated within a few months. If there's one thing Microsoft did right, it was keeping their APIs fairly stable over the years.
As a side note, even with garbage collection you still need to be aware of memory management and avoid "leaking references" to heavyweight objects and so stopping them from being garbage collected. (The classic case is sticking a reference to an Activity into a static variable, at which case that entire Activity with all its child views and resources etc. just sticks around forever until the static variable is overwritten.)
Comment on: An anonymous response to dangerous FOSS Codes of Conduct
Why is a random Google drive link shadier than any other anonymous hosting?
Comment on: The Ruby Programming Language community is now under siege by SJW entryists and the trojan horse Code of Conduct
These people are hardly taking over parliament. They're just as shy and socially awkward as most of us geeks, they just happen to have an axe to grind so they're going after what they see as the softest possible target.
Edit: It's not about making the whole world listen, it's about making someone - anyone - listen to them. So maybe "sociopolitical power" was the wrong way to describe it. They want their persecution complex validated and then their "persecutors" overthrown in front of a sympathetic audience.
Comment on: The Ruby Programming Language community is now under siege by SJW entryists and the trojan horse Code of Conduct
Simple. It's a way for people to gain influence despite lacking the technical skills required to gain influence by way of technical merit. It's not about oppression or discrimination, it's about sociopolitical power.
Comment on: Learn to Code. It's a LOT Harder Than You Think
And this is why everyone should have at least some basic training in programming. Not so that everyone can program, but so that those who can't will at least have some understanding of what goes into it, rather than "well I dunno what you do but it can't be that hard."
I've tutored university-level programming courses and in my experience there's a clear and definite gap between people who can learn to code and people who can't. And it's not just "how smart" they are - many people who can't code are highly intelligent, but nonetheless just aren't able to really 'grok' software.
Comment on: Programming for a Year and Need Direction
Start applying for entry-level Java jobs, and in the meantime, pick small projects and tackle them. Make sure you finish each project - completing projects is a skill that many programmers lack. The more projects you've seen through from start to finish, the more you'll learn about good design. Look at open source projects if you need example code. Read up on design patterns, but don't get obsessed with them.
Comment on: C#: Program Entirely with Static Methods. The result is more concise, readable and maintainable code.
If only there were a simple, powerful language that just uses static functions.
Comment on: Starting a tech startup with C++
^ That's actually a really good explanation. Also makes it clear why they used to be called 'data cubes'.
Comment on: Optimization of Computer Programs in C
A great read, but times have changed a lot. The only truly general advice about optimization is "profile your code, try to make the slowest bits faster, then re-profile your code to see whether it worked."
As I understand it (and I'm not an optimization specialist so I could be off-base here) on modern compilers and on desktop or server computers you want to avoid micro-optimizations like the ones listed here because the compiler does all that and more, and knows far more about the CPU you're running on, the states of the registers, etc than you do. Stick with making your code more efficient, precomputation, caching, algorithmic optimisations (for instance choose an O(n2) algorithm over an O(n3) algorithm and stay the heck away from exponential and higher orders unless really necessary). When you need that last 10% the top things to look at are cache performance and branch prediction type stuff. And again, always profile because you can get the weirdest interactions going on. Your intuition may/will be wrong but the numbers don't lie. Usually.
Comment on: What do you automate in your life with your programming skills?
Windows 7 start menu HAD THIS FEATURE, or at least part of it. You hit the Windows key and then start typing the name of a program or document. Windows 8 sorta does the same thing but the implementation is laggy and terrible.
Gonna check out this Everything thing, Launchy is pretty cool but it could do better with the matching algorithm (I'm used to Quicksilver on OSX which handles skipped letters and partial matches better.)
Comment on: What do you automate in your life with your programming skills?
Doesn't really count as "programming skills" but reticulation for the garden runs on a timer, and we've got a few lights and things running on timers/sensors so they turn on and off as required.
On my desktop (Win 8.1) I've found a huge productivity boost from installing Launchy. It's great being able to load any program or file with a few keystrokes.
Currently working on learning Android development and the Pebble protocol so I can start doing cool things with my Pebble watch.
Comment on: How to learn basics of sql in a simple way?
Last I looked at it, w3schools had a good SQL primer.
Comment on: [c] ACCU :: char* p vs char *p
I used to use char* p but switched to char *p for consistency when declaring multiple pointers on the line (eg. char *p, *q).
Comment on: It would be cool if someone built a system/protocol that could reduce jpeg transmission sizes by comparing parts of image to a local catalog.
Sounds like a cool idea, basically use your existing web cache as a giant lookup table. The tricky bit is how you let the web server know what images you've got cached, so it can say which ones to use as parts of the new image.
Also if you allow approximate matches (to improve compression ratio) you risk your images being subtly doctored by the algorithm, as Xerox did a couple of years ago.
Technically you may be able to find any bit string in the digits of pi (has this been proven? "it's infinite and doesn't repeat" doesn't necessarily prove it) but in general the index saying which digit the bit string starts at would take more bits than just storing the image directly.
Comment on: xkcd comic: Git
If the software is arcane enough that even the kind of people who choose to use C++ for a living have trouble with it, then it's a problem with the software.
Comment on: You Might Not Need jQuery
Because sometimes, all you want is a wheel. There's no need to cart an entire car dealership around with you everywhere you go.
Comment on: UK Programmer Releases Free Eye-Tracking Software for People With Neurological Disorders
Awesome!
GitHub link for anyone interested.
Comment on: Is having a Documentation Manager a good idea?
Exactly. API docs need to be written by the developers of the API. User manuals and the like need to be written by someone with an eye for detail and require a lot more time to be spent on presentation, so are easier for a documentation manager to work on. Office procedures and the like can also probably be done by a documentation manager.
Comment on: Passing a dynamic array into an OpenGL vertex buffer? Any thoughts.
Taking a shot in the dark here but you've only got one float per vertex there. Is numOfVerts meant to be the number of vertices or the number of floats? Or are you calling glDrawArrays() later with numOfVerts instead of numOfVerts/3?
Comment on: I hope one day I'll live in a country where I have freedom to write any code I like without fearing.
That was the summary. He lives in China, his government feels it has the right to control all internet traffic into and out of the country. The developer was developing a proxy that let Chinese people get to the internet without censorship. Police came to his house and told him to stop.
Comment on: I'm sorry for asking this here: HTMLPurifier isn't purifying submitted data, but it purifies a test echo.
Glad to help! :) It's the simplest mistakes that are always the hardest to spot.
Comment on: I'm sorry for asking this here: HTMLPurifier isn't purifying submitted data, but it purifies a test echo.
Ah ok, gotchya. Thanks for the full text, that makes it easier. :)
The problem is that you're purifying $Story into $clean_html, but then when you escape it, you're escaping the original $_POST['Story'] rather than escaping your purified $clean_html. So instead of this at line 86:
$clean_html = $purifier->purify($Story);
$clean_html = mysqli_real_escape_string($conn, $_POST['Story']);
you want this:
$Story = $purifier->purify($_POST['Story']);
$clean_html = mysqli_real_escape_string($conn, $Story);
Edit: Whoops, I got it swapped around too. Fixed now.
Comment on: I'm sorry for asking this here: HTMLPurifier isn't purifying submitted data, but it purifies a test echo.
So to be clear, your full code snippet looks like this?
$config = HTMLPurifier_Config::createDefault();
$config->set('CSS.AllowedProperties', array());
$config->set('CSS.ForbiddenProperties', array('height,width'));
$config->set('HTML.Allowed', 'u,p,b,i,span[style],p,strong,em,li,ul,ol,div[align],br,a[href],hr');
$config->set('HTML.AllowedAttributes', 'a.href,src,alt');
$config->set('HTML.ForbiddenAttributes', array('style'));
$purifier = new HTMLPurifier($config);
$_POST['Story'] = $purifier->purify($_POST['Story']);
$clean_html = mysqli_real_escape_string($conn, $_POST['Story']);
$sql="INSERT INTO published (Title, pageTitle, Story, Date)
VALUES ('$Title', '$Title', '$clean_html', '$Date')";
if (!mysqli_query($conn,$sql))
die('Crap.');
For starters, I'd suggest using prepared statements and bind_param() instead of inserting escaped text directly into the SQL text. Yes, it'll work but IIRC, prepared statements are more efficient.
Next, I'd suggest changing your code to print $_POST['Story'] directly onto the page, and (if you want to stay with your string-interpolation approach to the SQL statement) print out the SQL as well. That should let you know whether it's a problem with inserting into the database (maybe your DB user doesn't have write access?) or with the $_POST variable.
Lastly I don't know if there's any real reason not to do it, but writing back to $_POST feels icky. I'd suggest using a different variable to hold the scrubbed HTML.
Comment on: Developers Who Can Build Things from Scratch
There's two different scenarios at play here. There's "how to learn to develop software", which requires implementing a whole bunch of stuff for yourself at all levels of abstraction. The more of this you do, the better your design skills will be. Then there's "how to build something quickly and robustly for your employer", which requires you to efficiently use existing libraries to build something. Usually in the second case you're making some kind of utility application that doesn't do anything particularly new or exciting, and processing speed is far less important than simply getting it running quickly.
Comment on: I want to develop software for a living, but I suck at school. What are some certificates or programs outside of the college system that will prepare me for the workforce?
You aren't gonna like hearing this, but the ability to concentrate on something that you find boring is a critical, essential skill of software development. You need to work on your discipline as well as your technical skills.
Comment on: GitHub's new far-left code of conduct explicitly says "we will not act on reverse racism' or 'reverse sexism'"
That's what it looks like after the "majorities" are gone. He/she/it/they with the most differentiated race/gender/identification wins.
Comment on: GitHub's new far-left code of conduct explicitly says "we will not act on reverse racism' or 'reverse sexism'"
First they came for the white males, but I did not speak out, for I am an attack helicopter.
Comment on: GitHub's new far-left code of conduct explicitly says "we will not act on reverse racism' or 'reverse sexism'"
They did this to GIMP after the GIMP team moved to a different service. They stole the old GIMP account and wrapped the installer in crapware.
Comment on: Hey I'm trying to start learning programming but i am having a hell of a time starting. Is there a correct pathway to starting the adventure that is programming?
Figure out your motivation. You'll never get far if you just want "to program" without any real goal in sight. Why do you want to program? What do you want to build?
Get a grip of the basic concepts. Programming is like mathematics, in that every step builds from the last step. Start out with simple procedural programming - there are many suitable languages, I'd suggest starting with C (if you have access to a Linux machine) or Javascript (there are some great tutorials that run just in your web browser), and then moving on to either C++ or .NET. Other people will suggest starting with Python, Java or similar more 'modern' languages but IMO these languages require you to understand a lot of pretty advanced concepts in order to properly know what's going on.
Don't put too much store in coursework. Pick a project and work on it. When you're done, think about what went well, what didn't go well. Which bits of your project are solid and reliable, which bits make you feel a bit uneasy. Go back and fix up anything that you're not happy with. Spend some time polishing your project. Then pick another project and work on that. Don't be afraid to fail - the only way to fail at programming is by giving up. The internet has an almost unlimited amount of knowledge readily available if you need it.
If you want project ideas, once you're past the Javascript tutorial phase I'd suggest a series of small apps and games:
- 'Hello World': Gets you started. You'll be able to compile and run a trivial program.
- 'Guess the number from 1 to 100' text game: Gets you started with conditional statements (if/then), loops, text input and output.
- Mandelbrot Set picture generator: Gets you started with graphics output, windowing, event handling and more looping.
- Tetris: More advanced graphics, keyboard input, interactive real-time programming
Soon you'll have project ideas popping into your head all the time. The hard bit will be choosing which ones to do!
Comment on: Why the Open Code of Conduct Isnt for Me
This talks a great deal about offense and the right (or lack thereof) to 'not be offended'.
I think a far greater flaw with this code is the explicit statement that "we will not tolerate discrimination based on [...] technical ability".
The act of developing software explicitly requires technical ability. The machine will discriminate between correct and incorrect code. Their attempt to make technical competence irrelevant to the process of software development is inherently broken, and the fact that they suggest anything of the sort shows a deep lack of connection between the authors of the code and the subject matter they attempt to address.
Comment on: Learn Ruby by playing a video game.
Looks awesome, very reminiscent of CodeCombat. Too bad that these days I don't tend to bother learning yet another programming language unless someone's going to be paying me for it. :P
Awesome, good work!
The new 'atoi' looks good for what you want, the only thing I'd suggest is avoiding the call to pow() since it's generally slow and you can easily live without it. Also it might be more readable to write 48 as '0', it does exactly the same thing but the next person to read the code might not know that 48 = ASCII '0' off the top of their head:
:)