Welcome, Guest. Please login or register.

Author Topic: Beginners 'C' programing group  (Read 12913 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline melottTopic starter

  • Hero Member
  • *****
  • Join Date: Dec 2002
  • Posts: 989
    • Show only replies by melott
Re: Beginners 'C' programing group
« Reply #59 from previous page: February 13, 2004, 03:03:33 PM »
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
 
Stealth ONE  8-)
 

Offline iamaboringperson

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 5744
    • Show only replies by iamaboringperson
Re: Beginners 'C' programing group
« Reply #60 on: February 14, 2004, 06:05:52 AM »
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.
 

Offline FluffyMcDeath

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 3440
    • Show only replies by FluffyMcDeath
Re: Beginners 'C' programing group
« Reply #61 on: February 14, 2004, 06:35:20 AM »
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)
 

Offline boing

  • Sr. Member
  • ****
  • Join Date: Apr 2002
  • Posts: 293
    • Show only replies by boing
    • http://www.TribeOfHeart.org
Re: Beginners 'C' programing group
« Reply #62 on: February 14, 2004, 10:20:46 AM »
  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?
 

Offline mikeymike

  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 3420
  • Country: 00
    • Show only replies by mikeymike
Re: Beginners 'C' programing group
« Reply #63 on: February 14, 2004, 11:44:58 AM »
Quote
Still, why waste time with C when C++ exists?

Reading the rest of the thread might help :-)
 

Offline Cymric

  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 1031
    • Show only replies by Cymric
Re: Beginners 'C' programing group
« Reply #64 on: February 14, 2004, 02:38:07 PM »
@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 ;-)
Some people say that cats are sneaky, evil and cruel. True, and they have many other fine qualities as well.
 

Offline Karlos

  • Sockologist
  • Global Moderator
  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 16879
  • Country: gb
  • Thanked: 5 times
    • Show only replies by Karlos
Re: Beginners 'C' programing group
« Reply #65 on: February 14, 2004, 03:17:42 PM »
@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;
int p; // A
 

Offline FluffyMcDeath

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 3440
    • Show only replies by FluffyMcDeath
Re: Beginners 'C' programing group
« Reply #66 on: February 14, 2004, 10:58:54 PM »
Quote

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!)
 

Offline Karlos

  • Sockologist
  • Global Moderator
  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 16879
  • Country: gb
  • Thanked: 5 times
    • Show only replies by Karlos
Re: Beginners 'C' programing group
« Reply #67 on: February 14, 2004, 11:50:09 PM »
Quote

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...
int p; // A
 

Offline FluffyMcDeath

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 3440
    • Show only replies by FluffyMcDeath
Re: Beginners 'C' programing group
« Reply #68 on: February 15, 2004, 12:49:32 AM »
Quote

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? :-)
 

Offline Karlos

  • Sockologist
  • Global Moderator
  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 16879
  • Country: gb
  • Thanked: 5 times
    • Show only replies by Karlos
Re: Beginners 'C' programing group
« Reply #69 on: February 15, 2004, 12:59:27 AM »
This is beginning to sound like an 80's infomerical on the hazards of pointer abuse :lol:

Think before you dereference!
int p; // A
 

Offline Karlos

  • Sockologist
  • Global Moderator
  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 16879
  • Country: gb
  • Thanked: 5 times
    • Show only replies by Karlos
Re: Beginners 'C' programing group
« Reply #70 on: February 15, 2004, 03:04:54 AM »
Quote

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...
int p; // A
 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show only replies by Piru
    • http://www.iki.fi/sintonen/
Re: Beginners 'C' programing group
« Reply #71 on: February 15, 2004, 03:26:37 AM »
Quote

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.
 

Offline iamaboringperson

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 5744
    • Show only replies by iamaboringperson
Re: Beginners 'C' programing group
« Reply #72 on: February 15, 2004, 04:22:44 AM »
Quote
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.

Quote
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)

Quote
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.

Quote
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.
 

Offline iamaboringperson

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 5744
    • Show only replies by iamaboringperson
Re: Beginners 'C' programing group
« Reply #73 on: February 15, 2004, 04:37:35 AM »
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 :)

 

Offline FluffyMcDeath

  • Hero Member
  • *****
  • Join Date: Jun 2002
  • Posts: 3440
    • Show only replies by FluffyMcDeath
Re: Beginners 'C' programing group
« Reply #74 on: February 15, 2004, 06:14:03 AM »
Quote

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.