Amiga.org
Operating System Specific Discussions => Amiga OS => Amiga OS -- Development => Topic started by: melott on February 12, 2004, 05:57:53 PM
-
Well.. by popular demand, the beginners group
is going to be a 'C' group.
Several have expressed interest in this type of
group. So now is your chance to join.
You can send me an PMail or EMail or send an
EMail to ......
amiga_bcg-subscribe@yahoogroups.com
Hope to see you there.
-
This is a great idea! Anyone interested in learning C on the Amiga should join this group. No prior programming experience is necessary. I'll definately be there as a mentor for anyone who needs a guide so you won't be left out in the cold.
-
Why not C++? C is inferior.
-
Why not C++? C is inferior.
Because C++ is much more complex than C.
Because C++ is based on C (learning C++ is easier after C).
Because most of the software is written in C still.
Although I am myself too busy atm to help with this project I welcome the selection is C. Good choice.
-
Joined there... just in case I can offer some help :-)
There are also two other interesting Amiga programming groups:
http://groups.yahoo.com/group/amiga-c
http://groups.yahoo.com/group/MUI
amiga-c is bit more like "pro" but it is very good list for beginners too.
There are good message archives in those both lists.. Don't forget search option there :-D
-
I wonder how much my SASC 6.50 would go for these days. It's a whole C programming kit for Amiga.
-
Cool idea.
Why is it in the 'basic' area?
-
@Iamboring
The origonal group was going to be a Basic
group but do to popular demand its now 'C'
-
well lets write som stuff :-D
main() {}
it's a beginning :crazy:
-
@thread
Good luck with the learning. I applaud you choice of language. Contrary to most people's initial experience, C is actually quite logical and easy to learn once you get to grips with the syntax.
I wish I could devote some time for something like this, but I wish you all well.
-
A little test!
Which of the following is C ?
10 PRINT "HELLO";
printf("Hello, world!");
cout << "Hello, world!" ;
-
I know! I know!
:smack:
-
Is it strictly Amiga only? I'm Amigaless at the moment but I'd still like too learn C in a group.
The majority of the language is cross platform so hopefully there shouldn't be a problem.
Anyway, I want to learn programming so I can develop for the Amiga.
:-D
-
I'm trying to learn C though not on AmigaOS, at least not yet/considered it/sort of thing.
I'll get me coat :-)
... I tried to learn C once, off a guide on the net. They got the "Hello World" code wrong. I kind of gave up after that for a good long while :-)
I've now got a couple of books on the subject. I've yet to read them, but... :-)
-
I'm sure this would be good for other platforms too.
-
to get the hello world wrong ? :-P what a bummer.
#include
main()
{
printf("hello world\n");
}
:-P
-
Right. Here's the correct one:
#include
#include
int main(void)
{
printf("hello world\n");
return EXIT_SUCCESS;
}
-
Piru wrote:
Right. Here's the correct one:
#include
#include
int main(void)
{
printf("hello world\n");
return EXIT_SUCCESS;
}
I would have returned zero at the end... bad?
-
@tpg
No. EXIT_SUCCESS is technically implementation defined but is pretty much zero everywhere.
-edit-
That's no as in its not especially bad ;-)
-
Now which one is true? :-)
Or do both work the same? Maybe both work the same, but the later one is just a bit bigger in bytesize only? :-D
-
what happened to (int argc, char *argv[] ) ?
-
One thing about C is that its definition of the main function has become fudged over time.
Originally, main was defined thus:
main()
As time went on, C got a bit stricter with its function definitions and main, which technically returns an integer was redefined to explicitly show this
int main(void) - used when no start parameters are used, or
int main(int argc, char** argv) - used when you want to access whatever was passed on the command line.
To remain compatible, a lot of implementations still allow the original old definition.
The best advice. Use an up do date C compiler and use explicit integer return type definition of main (ie either of the second two above).
-
To remain compatible, a lot of implementations still allow the original old definition.
(Just to confuse things) Like this: ?
void main(argc,argv)
int argc;
char **argv;
{
...
}
er... if that's how it's done, it's been such a long time since I've programmed that way...
I could be wrong
-
@iama
If you code that with ANSI rules enabled it will fart at you and say K&R syntax is depricated ;-)
-
:lol:
-
I havent had to define main in any of my C++ projects for over a year now..
I bet Patrik knows what I mean ;-)
-edit-
Better stop before I drag the thing totally off topic!
-
Karlos wrote:
I havent had to define main in any of my C++ projects for over a year now..
I bet Patrik knows what I mean ;-)
Could mean anything...
You've been working on the same projects for over a year? :lol:
-
iamaboringperson wrote:
You've been working on the same projects for over a year? :lol:
Laugh it up mate, laugh it up. I moved on to Application class based coding ages ago. I havent defined main() in any projects started in the last year as I havent needed to :-P
-
Laugh it up mate, laugh it up.
:roflmao:
-
I guess he did, too :-)
-
Look, guys.. I think its great to learn C and all, but doesn't it really depend on what kind of project you want to work on?
Writing games and programs where you are trying to push performance to the limits may benefit from C which compiles to the native system better than C++ and tends to run faster.
However, I would imagine that creating AmigaOS apps using a standard C++ class library would be easier than a bunch of C routines with a zillion parameters.
C++ can actually be simpler to learn than C if one sticks to the simpler aspects. C++ can be a higher level language, and thus easier to learn, than C.
For example a C++ string object with overloaded operators makes text manipulation a zillion times easier than in C. Changing properties and running methods to manipulate a control of some kind, is, I am sure, easier to do utilising OOP than lower level C calls.
If someone wrote a standard class library similar to .NET or Java(AWT or SWING) for manipulating windows and various system standard objects etc. (I don't know if one already exists) then newbies would be able to get things up and running quickly in a high level language. It is these sorts of developer shortcuts which have made programming for the Microsoft platform so popular and easy to do.
I would not expect Newbies to build class hierarchies and the like themselves but having them in existence in some sort of toolbox would shortcut development time and lower the threshold for programming in AmigaOS. Everything should be abstracted for the newbies. Remember the whole nature of the new OS rewrite was to keep away from the metal so the rationale for writing in C or assembler and directly hitting the hardware is no longer there.
I think ease of development so that new titles can be written for the platform is far more important that writing a 3d routine that runs milliseconds faster than before. WE NEED NEW SOFTWARE.
If no one does this I would happy to write object wrappers myself which mimic the behaviour of more Rapid Application Development environments like Microsoft's.
I know we all hate Microsoft Winblows, and sometimes MS's over complexity makes you want to pull your hair out but they really have their act together in terms of their development support.
That's my 2 cents.
-
Maybe the reason so much Windows software is a fat mess is down to programmers who don't understand what the functions they are calling do at a basic level.
-
Nah, it would be best to stick with C, and cover the exact same things as in the ARKRM's & NDK, etc...
Stick to standard stuff.
MUI wouldn't be too bad later on also
-
I asked some techie friends a while back what they thought would be the best language for me to really get into programming. They all suggested C. So here I am :-)
-
@thread
Sorry, going off topic...
@BigBenAussie
I have been developing a cross platform C++ class library for rapid application (specifically game/multimedia) development.
Presently it is only amigaos implementation level, but it none of the classes expose system level stuff. It handles kernel services, io, gfx, sound, etc. via a set of interfaces and wrappers.
It took 10 mins to write this silly goo clone (http://www.amiga.org/gallery/index.php?n=537) using these class libraries in their current state.
If c++ is your thing, the source for the above program (but not the class libraries themselves ;-) ) is all here (http://www.nyteshade.com/karlos/cpp/warp.cpp).
(I use a tab of 2 spaces if the source looks screwy)
-
BASIC is a waste of time
C is the best because most of the same code can be used under AmigaOS, MorphOS, and AROS, and you can actually program some decent games and utilities with it.
You don't need objects, streams, classes, templates, vectors etc. for good software for Amiga!
Pluss if you want to learn the standard and normal way to program on Amiga, then Intuition, GadTools, and BOOPSI all use plain C.
-
#include
#include
int main(void)
{
printf("hello world\n");
return EXIT_SUCCESS;
}
I think strict ANSI-C code would look like this
#include
#include
int main( void )
{
printf("Hello world!\n");
exit(0);
}
and here's something funny about "Hello world!" programs:
Evolution of a programmer (http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html)
-
Not sure if this is going off topic.
I would imagine that a lot of programmer newbies want to play around with 3d, it being such a cool thing.
What do they want to do anyway?
@Karlos
About that 3d C++ library you've written. No offense, but is seems you would also need to incorporate a mighty good tutorial and simple documentation for it to be useful, at least to a newbie.
Has any one thought of talking to, or joining the Cross Platform Open Source Crystal Space 3d group and getting them to do an AmigaOS port.
http://crystal.sourceforge.net/tikiwiki/tiki-index.php?page=About+Crystal+Space
?????
I guess it is off topic as Crystal Space 3d is sure to be too complex for newbies.
Sorry, I've written it now.
-
@BigBenAussie
The library actually a set of abstractions comprising a complete framework, not just 3D. Also, it's not for newbies, its for experienced lazy b*stards...
Hence the "off topic" remark ;-)
-
I have missed all of this conversation, so forgive me if this has been discussed already.
May I suggest you not take this group private? Do it right here on A-Org, there are already forums for develpment. If it really is going to be a big movement I'm sure you can convince the webmasters of AO to create a new forum. Something like this could be VERY useful to get people onboard, and where else better to have it than here where it can get maximum exposure? Heck if I ever get free time I'D like to learn some programming:-) Freetime is a big IF though :-/
-
@red
I was thinking the same as the thread unfolded. It could be a very positive thing to have out in the open, readily available...
-
May I suggest you not take this group private? Do it right here on A-Org,
I agree. I don't see why people want to take this elsewhere...
-
Perhaps to avoid off topic discussion and trolling?
I'm not saying it will definately happen, but you know how it is when people think their solution (and I am as guilty of this as anybody) is better than someone elses and a perfectly simple question gets dragged into a long discussion going way off topic...
...like I am now :lol:
-
Hmm, yes that's one point against. ;-)
Maybe some cross-polination is in order.
(Wonder what Cyberus will be able to read into that comment?)
-
@crystall
I think strict ANSI-C code would look like this
#include
#include
int main( void )
{
printf("Hello world!\n");
exit(0);
}
Possibly. However, EXIT_SUCCESS can be used instead of 0, and in general, if there is a define to use, use it instead of fixed value (that way if things would ever change, your code will adapt with just recompile and you don't need to worry about changing all the fixed constants in the code). This is more like generic programming style, not ANSI standard.
I think ansi does state that 0 is "success" for exit(), however. So you're correct here.
Anyway, use of exit() instead of proper failure code path is a bit dull, and forces you to write cleanup stub routines with atexit(), and thus forces you to use global variables. I would advice coders to stay away from exit() if possible, esp if coding for AmigaOS, MorphOS and other compatibles.
The problem is that there is no automatic cleanup for OS resources, just for resources set up by the startup code (stuff provided by the ANSI standard, for example: malloc()d memory, filehandles opened by fopen() etc). So if you would open a intuition window and call exit() to terminate, the window would not get closed (unless if you do it with atexit cleanup stub routine).
Now I got carried away, sorry. :-)
-
that_punk_guy wrote:
(Wonder what Cyberus will be able to read into that comment?)
Everything.
-
Karlos wrote:
Perhaps to avoid off topic discussion and trolling?
The site crew here is very laid back and open to suggestions. If a forum needed strict moderation to keep trolling out, I'm sure they would be open to the idea.
Just my educated guess. :-)
-
Could be a problem with posting code on the forum though. Particulary anything with square brackets or nested code where tabbing is necessary for clarification.
-
@red
There is a tutorial forum already, right? You could create a C Tutor forum in there with some stricter moderation and various people on hand to answer questions. You'd need to keep an eye on the level of discussion some answers can generate, 'experts talking shop' can go off topic quickly, leaving the person asking the question more confused than before they asked.
Judging when people are going down this route as opposed to genuinely answering questions to the best of their abilites will be the tricky part, IMO.
-
Karlos wrote:
@thread
If c++ is your thing, the source for the above program (but not the class libraries themselves ;-) ) is all here (http://www.nyteshade.com/karlos/cpp/warp.cpp).
That's mighty pretty, Karlos, but I must quibble.
in:
if (thing) delete thing;
The test is redundant (delete NULL is safe).
if(!thing)
{
errorPopUpThingy("failed to alloc thing");
}
won't ever happen unless you use operator new(no_throw)
else new throws bad_alloc which you'll need to catch.
-
Well I'm interested in the idea, so chances are I'd frequent it probably more often than moderators just 'checking up', so I think you're safe there :-)
-
FluffyMcDeath wrote:
That's mighty pretty, Karlos, but I must quibble.
in:
if (thing) delete thing;
The test is redundant (delete NULL is safe).
if(!thing)
{
errorPopUpThingy("failed to alloc thing");
}
won't ever happen unless you use operator new(no_throw)
else new throws bad_alloc which you'll need to catch.
@Fluffy
You are absolutely correct about the no_throw, but I'm afraid you are assuming too much.
-edit-
Is it me, or does the above sound like it should have been wrapped in a sort of typical "James Bond villian" tag? :-)
-/edit-
Part of the reason the framework itself isn't pulbic yet is that it was written in that 'less than stellar c++' compiler, StormC.
Exceptions are not used by any of the components because I discovered early on that the exception mechanism in storm is broken (http://www.amiga.org/forums/showthread.php?t=525).
Its fine in single thread programs, but the framework defines a Threadable service class (kind of like a fusion of java Thread and java Runnable interface) that allows the class inhertiting the service to have its own internal thread of execution.
I discovered that in multithreaded code, the thread which throws an exception is hardly ever the one to catch it. That is, StrormC's implememntation doesn't do the book keeping.
StormC, even with exceptions enabled doesn't support new(no_throw) in any case, nor does it safely check the null pointer case for delete.
Basically any oddities you see are all down to the fact that I started in StormC++ which was a mistake.
The whole framework code will be moved to gcc which will hopefully not be too much of a problem since I don't use any storm dependent features (other than the ide). Some asm code exists in places (optimised versions of various methods).
Post gcc plans are to use proper exception based error handling (to replace the existing return value model) and probably some namespace resolution for libraries.
First things first, the code will be ported as is. Then exception handling introduced to replace the existing error returns (in places where a genuine error exists, rather than something better represented by a bool return etc.).
The gcc port will also make the cross platform coding a lot easier. Currently the windohs version is maintained in open watcom....
-
BigBenAussie wrote:
Look, guys.. I think its great to learn C and all, but doesn't it really depend on what kind of project you want to work on? [...] However, I would imagine that creating AmigaOS apps using a standard C++ class library would be easier than a bunch of C routines with a zillion parameters.
It was about a learning to code-group. That's not the same as a creating AmigaOS apps-group, which requires much more insight into what can be done and how to do it. And aren't you slightly exxagerating the 'zillions' of parameters? I've rarely used more than 4 parameters to a function; if I need more, the function is too complex and must be split up.
C++ can actually be simpler to learn than C if one sticks to the simpler aspects. C++ can be a higher level language, and thus easier to learn, than C.
For example a C++ string object with overloaded operators makes text manipulation a zillion times easier than in C. Changing properties and running methods to manipulate a control of some kind, is, I am sure, easier to do utilising OOP than lower level C calls.
Don't forget you can abstract a helluvalot in C as well using a simple link library. Good C-code already implements a lot of the OO-methodology, with C++ offering more advanced and standardised features. Besides, do you really want to explain operator overloading and the confusing and arcane type promotion rules of C++ to a newbie? Otherwise he will blow both feet and parts of his legs away in the time it takes you to blink.
I would not expect Newbies to build class hierarchies and the like themselves but having them in existence in some sort of toolbox would shortcut development time and lower the threshold for programming in AmigaOS. Everything should be abstracted for the newbies.
Then they're better off with an interpreted scripting language such as Python or Ruby. They don't crash your machine, are very forgiving, and come with tons of 'glue' to link to toolkits, networking libraries, graphics subsystems, and so on. Even C++ looks very primitive and arcane compared to coding setups like these. It is also perfect for rapid prototyping, which can then later on be redone in C++ for speed.
Remember the whole nature of the new OS rewrite was to keep away from the metal so the rationale for writing in C or assembler and directly hitting the hardware is no longer there.
I'm afraid you got that quite wrong. There was never any need to hit the bare metal. People were just not used to program a multitasking environment and therefore made quite illegal assumptions about how the computer allocated its resources. They also thought that the OS would 'hinder' them in what they wanted done. They saw the Amiga as a C64 on steroids, not as a simple but fully functional Unix-machine. Even in the case of the Pegasos and the AmigaOne, I could hit the hardware if I wanted. Of course the OS doesn't (easily) let me, and quite frankly I have no idea what registers and stuff I need to fiddle with, but...
The rationale about the rewrite is to remove the hardware dependencies of the old AmigaOS, both in terms of the CPU as the old custom hardware. Also lots of bugs will be fixed, as well as implementation of much-needed extensions on a fundamental level, rather than tacking them onto the OS in the form of unstandardised user libraries.
I think ease of development so that new titles can be written for the platform is far more important that writing a 3d routine that runs milliseconds faster than before. WE NEED NEW SOFTWARE.
And that is very, very true.
-
Remember the whole nature of the new OS rewrite was to keep away from the metal so the rationale for writing in C or assembler and directly hitting the hardware is no longer there.
I'm afraid you got that quite wrong. There was never any need to hit the bare metal. People were just not used to program a multitasking environment and therefore made quite illegal assumptions about how the computer allocated its resources.
While he did get that quite wrong, so was your explanation :-)
Assembly for example hits the hardware directly. The programmer tells the computer what memory/chip addresses he wants to reference, and the computer will access those exact addresses. If they don't exist, the program will fail in one way or another. Assembler is what's known as a "low level" programming language. You pedantically and exactly program the computer. You also need to use an implementation of Assembly that matches your CPU.
C is a higher level programming language than Assembly. So for example you can use a compiler called 'gcc', which is written for particular operating systems and certain architectures like x86 (rather than a particular x86 CPU). If you program in C, most of the legwork in specifying memory ranges for your program is done for you (though I don't know much about C, I think you can do things like specify particular memory ranges if you needed to).
Getting back to the point. There's a reason why programmers "hit the hardware" directly. Program performance is a damn sight better, and while Assembly programming is extremely pedantic, it is more flexible. But you couldn't write a program to run on a modern operating system in Assembly, because the OS handles memory, cache, and hardware resources, it would tell your nasty little program that tries to circumvent it to get stuffed.
If say AmigaOS were completely written in C and then used on stock Amigas, it would be slower. Most of the performance and responsiveness is derived from hitting the hardware directly. OS4 is virtually a complete re-write from previous versions partly because of the architecture change, but mainly due to how the previous versions were programmed.
Someone can probably do a better job of explaining than I can :-)
-
@Cymric
I tend to agree. C is the starting point for someone new.
You need to know C syntax, functions and structures before you have the knowledge base to truly take in what a class is. That's before you get into stuff like overloading, generic programming etc.
One of the things which Bjarne Stroutsrup himself notes in his C++ Language book is that "a good C program is also a good C++ program."
-
@mikeymike
You'd be surprised for a "high level" language how low level C really is. Its much lower level than BASIC type languages and as a compiled language it is faster mostly due to the fact that it is quite close to the machine level already.
The beauty of C is that it gives you high level abstractions for things which are a pain (and non portable) to do in asm, without really being much higher.
-
You'd be surprised for a "high level" language how low level C really is. Its much lower level than BASIC type languages and as a compiled language it is faster mostly due to the fact that it is quite close to the machine level already.
Which is why I said "higher level" :-)
-
@mikeymike
/me needs stronger specs :-)
-
mikeymike wrote:
While he did get that quite wrong, so was your explanation :-). [...] Getting back to the point. There's a reason why programmers "hit the hardware" directly. Program performance is a damn sight better, and while Assembly programming is extremely pedantic, it is more flexible. But you couldn't write a program to run on a modern operating system in Assembly, because the OS handles memory, cache, and hardware resources, it would tell your nasty little program that tries to circumvent it to get stuffed.
If say AmigaOS were completely written in C and then used on stock Amigas, it would be slower. Most of the performance and responsiveness is derived from hitting the hardware directly. OS4 is virtually a complete re-write from previous versions partly because of the architecture change, but mainly due to how the previous versions were programmed.
You are right when you say that assembly allows for unprecedented control over the computer. You sometimes have to use it, simply because the things you want done do not have a higher-language equivalent. Program performance isn't as clear-cut, however. Programming in assembly does not automatically make your code fast. You can write incredibly sloppy code in assembly if you want to (or are not careful). 15 to 20 years ago, optimisation algorithms weren't as good as they are now, and people preferred to do things directly in assembly rather than optimise the ever changing output of a C-compiler. 'Slowness' of compiler code had little to do with not being able to directly access custom chip registers or specify addresses by hand: it was almost always a case of unnecessary loop constructs and variable usage. Humans were simply better than the compiler in distinguishing 'good' from 'bad' code, and in some cases could streamline code for global performance. Compilers are still bad at this, as their view is rather localised.
The problem was that many would-be coders did not know how to properly code the Amiga, or looked upon the OS as an enemy instead of their friend. They sought illegal shortcuts mostly because of misguided ideas about 'efficiency'. I doubt that these practices would be the rationale for the rewrite of AmigaOS to version 4; people nowadays understand very well how the Amiga should be programmed and no longer resort to illegal tricks. It's the quickest way to assure that your code won't even run on today's generation of Amigas.
By the way, AmigaOS was largely written in C. Only a few core parts were done in hand-crafted assembly for efficiency. (One ill-fitting part, in BCPL, was hammered and stapled into place, ruining an otherwise elegant design in the process. That part is now completely out of AmigaOS 4.) The responsiveness was not due to the fact that the hardware was hit directly, but simply because the system had relatively lots of computing resources to begin with, while omitting memory protection.
-
Hello All ....
It has been suggested that this Beginner 'C'
group be taken public here a A.Org.
I don't think that would work. The total amount
of EMail that this group is already generating
would soon bury A.Org and nobody would want to
wade through all of it to find an answer to a
question. The thread would be just to big, already,
this thread is longer than most want
to scan through.
I do see where a forum here at A.Org could be
created for indept discussion of the merits of
coding this way or that.
I think if a forum was started like this it
would need a cap on the number of post in it at
any given time, say 20 or 30 posts and the oldest
posts just dropped off and let the forum run
continually.
That might work
-
May I make a suggestion?
Perhaps all of the best tips, tutorials, and other lessons etc. could be compiled into one archive. Perhaps an AmigaGuide document could be made out of it.
This could be the ultimate reference and tutorial that could replace the RKRM's and NDK.
-
C is easy and difficult.
For the most part you don't really need to know what is actually going on and you can just go with the semantics. But, once you get into pointers it's good to know what is going on "under the hood" so you know why things like:
char * clone(char * string)
{
char result;
strcpy(&result, string);
return &result;
}
are so bad.
(The finger that points at the moon, is not the moon)
(Build not thy house upon the shifting sands)
-
I don't think I'll ever like C. It looks like something created for a parser that was written in one night instead intended as a quality language. One can have a great language without the visual ugliness of C. Or it's counterintuitive use of grammar and math characters. It's just the most goddamn impossible language tp read through that I've ever seen.
As far as I'm concerned, either use Assembler, or use AMOS or Blitz. Anything inbetween is kind of pointless.
Having said that, I guess I'd like to revisit C since so much $&^@ documentation assumes you're comfortable with it. Bastards. This is what happens when wannabe's outnumber true coders in colleges.
Still, why waste time with C when C++ exists?
-
Still, why waste time with C when C++ exists?
Reading the rest of the thread might help :-)
-
@Fluffy:
Erm... *that* is wrong, and *that* too. This code will segfault a Unix-machine, and crash an Amiga faster than a politician can shift positions. Indeed, pointers are tricky ;-)
-
@Cymric
Fluffy isn't wrong, he is saying when you understand pointers properly, you know *why* the code he presented is so screwed up.
-edit-
It appears the 'bad' code is to make a function that will create a new unique copy of the source string.
-/edit-
For those who can't see it
First of all, he creates a single character 'result', gets a pointer (the address of the bit of memory where 'result' is) to it by using '&result'.
Next, he attempts to copy a string of characters to that piece of memory using a standard C function 'strcpy()' for copying strings. Strings in C are basically arrays of characters (that end in a zero byte). When you copy them, you copy the entire array from one place to another.
The result is that the memory beyond the space occupied by 'result' is overwritten. Variables like the one he declares here are created on the programs' stack, where all the important temporary information at any given instant lives. The effects of overwriting this memory are hence generally catastrophic to say the least...
The second error is that he returns the address of 'result' from the function. The problem here is that the actual character 'result', created on the stack, only exists during the lifetime of this function. Once you leave the function (by returning from it), that character effectively ceases to exist and its memory space is used by something else.
By returning its address, we can then later go back and use this variable which as we have just seen, no longer really exists. Any attempts to use the variable involve, once again, illegally messing up the stack resulting in another bomb out.
-edit-
Anyway, to fix this bad code, we need to create a genuine, seperate copy of the string and return its address. This means we need to dynamically allocate (that is, create an area in the computers 'free' memory) sufficient space to store a copy of the string, copy the characters accross and then return the address of this new bit of memory we have floating around.
char* clone(char* string)
{
char* result;
result = (char*)malloc(strlen(string)+1); /* Don't be a muppet like me and forget the +1 :-) */
strcpy(result, string);
return result;
}
This can be improved upon by checking that the allocation using malloc worked (check the value of 'result' to make sure it is not NULL) before we use it, but I ommited this check for the sake of clarity.
ie instert after the line with malloc() and before strcpy() the following check
if (result == NULL)
return NULL;
-
Cymric wrote:
@Fluffy:
This code will segfault a Unix-machine, and crash an Amiga faster than a politician can shift positions. Indeed, pointers are tricky ;-)
What's really amazing is how often code like this WON'T bring the Amiga or many other systems down right away. If this code is executed at the end of a long sequence of calls, and it doesn't write past the end of the stack (or even if it does for that matter) and the stack never goes that deep again, there is no reason why the data can't live for ever and be manipulated at will. It's just memory.
However, it could bring down a completely different task on the Amiga if it writes past the end of the stack, or maybe, one day when you add a feature you step on this landmine and try to find the bug in your code for days before finding this pre-existing unexploded bug in some code that got there long before you did.
(BTW I just compiled this with a version of gcc at work that we use for our embedded systems. It didn't even warn!)
-
FluffyMcDeath wrote:
What's really amazing is how often code like this WON'T bring the Amiga or many other systems down right away. If this code is executed at the end of a long sequence of calls, and it doesn't write past the end of the stack (or even if it does for that matter) and the stack never goes that deep again, there is no reason why the data can't live for ever and be manipulated at will. It's just memory.
Actually, it brings amigaos down with a thump almost immediately. Remember, the stack grows downwards on amiga/680x0 so as the copy writes to succesively higher addresses, one of the first things it will trash is the functions return address which was pushed by jsr onto the stack right after all of the arguments.
Hence it doesn't matter how deep into the code you are, once you overwrite your functions' return address you are shafted...
-
Karlos wrote:
Actually, it brings amigaos down with a thump almost immediately. Remember, the stack grows downwards on amiga/680x0 so as the copy writes to succesively higher addresses,
... oh yeah! See how confusing this can be? :-)
-
This is beginning to sound like an 80's infomerical on the hazards of pointer abuse :lol:
Think before you dereference!
-
FluffyMcDeath wrote:
BTW I just compiled this with a version of gcc at work that we use for our embedded systems. It didn't even warn!
Realistically I don't think it can warn against the first misuse (since it is technically not invalid in the language) unless the error checking does some kind of flow analysis to see that &result is a actually reference to a single character.
However, returning the address of an automatic variable should definately give a warning. Even StormC manages that...
-
char* clone(char* string)
{
char* result;
result = (char*)malloc(strlen(string));
strcpy(result, string);
return result;
}
Now, the code above trashes one byte past the allocated memory. That is because strlen() return the string length without the terminating zero. strcpy() will write this zero-char and trash one byte past allocated memory. This is a common beginner mistake. Now, this won't be the last time we meet an error or bug, and we should not get depressed if we make them. Mistakes are good, since often you learn much more from fixing them than always writing perfect code.
To fix this bug, we must add one to strlen() result to make room for the terminating zero-char:
char *clone(const char *string)
{
char *result;
result = malloc(strlen(string) + 1);
if (result)
{
strcpy(result, string);
}
return result;
}
NOTE: 'const char *string' indicates that the memory pointed by the string pointer is read only, and not modified by the function. This is not really needed, but helps to locate programming mistakes (here: accidently modifying read only parameter) in the function.
-
I don't think I'll ever like C. It looks like something created for a parser that was written in one night instead intended as a quality language. One can have a great language without the visual ugliness of C. Or it's counterintuitive use of grammar and math characters. It's just the most goddamn impossible language tp read through that I've ever seen.
For a programming language, C is actually quite sexy. You'll notice this once you become familliar with it.
As far as I'm concerned, either use Assembler, or use AMOS or Blitz. Anything inbetween is kind of pointless.
Inbetween? BASIC is pointless!
C is structured, and perfect for large projects that need standardization and portability.
In short C is the most practiable of them all! (C++ also)
Having said that, I guess I'd like to revisit C since so much $&^@ documentation assumes you're comfortable with it. Bastards. This is what happens when wannabe's outnumber true coders in colleges.
It has a reletively steap learning curve. That's all it is.
Still, why waste time with C when C++ exists?
If you don't like C for the reasons you explained above, you'll probably hate the idea of C++
C is probably better to learn for Amiga programmers.
It's also easier to learn.
-
Re: Pointers in C
People do find pointers tricky, and I guess that could be due to the fact that people don't really understand what they are.
Not that I reccomend going out and learning assembler just to under stand them, but I knew assembler before I started learning C, so I knew about addressing already.
Some of the code looked a little funny (ampersands and asterisks infront of variable names), and when I realised that a 'pointer' was actually just an address of a particular variable or structure, it became so much easier.
I think it's important to learn how functions are entered and exited. And to learn about how the stack works, that may solve some peoples problematic programming - like what fluff 'pointed' out.
One problem I had when I started learning C, was understanding how functions worked. I could define them etc. however I treated function calls like 'gosub' or 'goto' in basic.
What I would sometimes do, is if I wanted to 'goto' the top of the function, I would just thisveryfunc() there!! Of course a program doing that will easily run out of stack space after a while! (yeah.. recursion...)
Recursion I think is a fairly advanced subject, the only use for it that comes into mind at the moment (although there are many more) is traversing binary trees etc.
People who are used to Basic and Assembler need to get used to the idea of local variables, too :)
-
iamaboringperson wrote:
Re: Pointers in C
One problem I had when I started learning C, was understanding how functions worked. I could define them etc. however I treated function calls like 'gosub' or 'goto' in basic.
And also missed out on the joys of function pointers by which you could tell someone else where to goto!!
So, it seems that avoiding pointers is probably a good thing to do for beginners, but programming for the Amiga is riddled with pointers cos they're soooooo useful (especially on slower CPUs when passing large structs by value would be painful).
Another thing that came to mind is the problem of overflow. Since C is pretty close to the metal, it is necessary to know about the number of bits you have in your ints. It's not an arbitrary size and precision environment.
Ooooh, and endianism!!
Oh, and compiler optimizations that blow non volatiles out of your hardware banging code, and ... all sorts of good stuff.
Lot's of gotcha's in C/C++. Still great fun though.
-
@Piru
Whoops, I knew I'd forgotten something :-D I thought about the +1 afterwards and thought "I don't remember - do I need it or not?"...then went to bed :-)
-edit-
It also suggests that this isn't even a beginner mistake ;-) Perhaps I should go join Matt and play with lego in the corner :lol:
-
boing wrote:
I don't think I'll ever like C. It looks like something created for a parser that was written in one night instead intended as a quality language. One can have a great language without the visual ugliness of C. Or it's counterintuitive use of grammar and math characters. It's just the most goddamn impossible language tp read through that I've ever seen.
Written in one night? :lol: C has the just about cleanest syntax going. Java, javascript, C++, CF, etc. didn't copy it for fun, you know.
Still, it does look a bit odd at first, but with experience you will actually realise its stuff like BASIC that is unweildy.
As far as I'm concerned, either use Assembler, or use AMOS or Blitz. Anything inbetween is kind of pointless.
1) Don't use assembler unless you either (a) don't care at all about portability, or (b) optimising some code for a particular system.
2) AMOS is one of the worst languages ever. Period.
Having said that, I guess I'd like to revisit C since so much $&^@ documentation assumes you're comfortable with it. Bastards. This is what happens when wannabe's outnumber true coders in colleges.
A very mature attitude! A bad craftsman always blames his tools. If you are a 'true coder' as you say and have the mentality for programming (that is analysing problems and devising solutions) you can adapt to just about any language.
Since I studied chemisrty, I learned 680x0/PPC asm, C, C++ and Java entirely in my own time. I also started with a knowledge of BASIC and can assure anybody that moving to C from such a background is far from impossible.
Still, why waste time with C when C++ exists?
If you can't take C syntax, you don't stand a chance of learning C++
-
Since I studied chemisrty, I learned 680x0/PPC asm, C, C++ and Java entirely in my own time. I also started with a knowledge of BASIC and can assure anybody that moving to C from such a background is far from impossible.
Which remindes me that in one course I took, we had to program in C for a couple of the digital electronics modules. (Interfacing with hardware we assembled)
C is not just a language that 'programmers' who are employed to only program use. It's probably used in many other professions also. I could imagine that electronics engineers these days probably couldn't get very far without a little programming experience.
And C is probably the best language for scientific use.
-
iamaboringperson wrote:
Re: Pointers in C
Recursion I think is a fairly advanced subject, the only use for it that comes into mind at the moment (although there are many more) is traversing binary trees etc.
Or for drawing bezier-curves that are precise, but won't waste precious cycles by
creating to much points .......
:-x :-P :-o :-D ;-) :roll: :evil: :oops: :-P :-x :idea: :madashell: :griping: :boohoo:
-
Written in one night? C has the just about cleanest syntax going. Java, javascript, C++, CF, etc. didn't copy it for fun, you know.
Still, it does look a bit odd at first, but with experience you will actually realise its stuff like BASIC that is unweildy.
The C-syntax was copied because it is what most
programmers are used to already.
Syntactically its a piece of ***.
And lets not talk about C++.
No, C has other things going for it:
Lots of Examples,documentation,books,teached in schools,
and implementations on every possible platform.
A bit like Windows :)
Edit:
[if you disregard implementations on every platform :)]
-
Excuse me? The fact that you don't like C's *logical*
syntax doesn't make it #OOPS#. The fact that boing prefers
AMOS' syntax over C's just makes him crazy:-)
-
The C-syntax was copied because it is what most
programmers are used to already.
Oh dear..
No, it's copied because that's what programmers prefer
Syntactically its a piece of ***.
And lets not talk about C++.
Both are great languages
What language do you prefer?
Don't tell me Pascall.... or BASIC.... or *eeck* COBOL...
Excluding the look-a-like clones, C is the most structured and best designed programming language out there.
-
Karlos wrote:
@Cymric
Fluffy isn't wrong, he is saying when you understand pointers properly, you know *why* the code he presented is so screwed up.
Yes, and that's precisely what I had in mind when I wrote my message. I wasn't trying to point out that he had made those mistakes unknowingly, I was trying to tell him (or her) that I saw how many errors he had deliberately introduced without giving away what they were. Plus expressing my consent that it's easy to shoot yourself in the foot with pointers. Hope that clears up some confusion!