Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I need some help with using memory! (C)
#11
I dont got any manual for my c compiler or atlist not one who deals wit the syntax of stuff.
Reply
#12
could I use calloc my book tells me its like malloc but better?
Reply
#13
Shogun, if you are using a Unix system you can look for help in the man pages.
Code:
man malloc
Will give you the syntax, usage, return values and any bugs you need to be aware of when using malloc. If you dont have a Unix system, you can try typing the above into google (careful about portability issues though) to get an online man page.

calloc is very similar to malloc, it is defined as follows:
Code:
void *calloc(size_t nmeb, size_t size);
calloc allocates nmeb elements of size bytes. The major difference between calloc and malloc is that calloc zeros memory before allocating it (this is good if you are a security freak). To allocate space for ten integers (using Na_th_an's example):
Code:
int main(void) {
  int *array;

  if((array = calloc(10, sizeof(int))) == NULL) {
    fprintf(stderr, "Error, not enough memory\n");
    exit(-1);
  }

  /*
   * And the rest is exactly the same as Na_th_ans example
   */
}

The only major difference in syntax is that calloc allows you to specify the number of elements as a parameter rather than working it out yourself with malloc. My coding style also differs slightly from Na_th_an's, I prefer to have the NULL test in the same block of code as the actual malloc/calloc (See if you can figure out how the parenthesis and assignments work), I also dont cast the return value of calloc because standard C doesnt require that you do and I use standard C complaint comments! (Glares at Na_th_an :evilSmile. I use fprintf(stderr, "..."); for portability reasons (Unix in particular distinguishes heavily between stdout and stderr. Another good point to pick up from Na_th_an's code is that he uses exit(-1); when there is an error, this allows any calling program to check the return value of the entire program to see if there was an error.

Your question for reallocating memory has /almost/ the right code:
Quote:
Code:
int array;
int i;
for(i=0;i<300;i++)
{
  /*the code does somthing*/
  array = (int *) malloc (i * sizeof(int));
  /*the code does somthing else*/
}

With a few changes:
Code:
int *array; /* You need a pointer to malloc to */
int i;

array = malloc(sizeof(int)); /* No error checking for brevity */

for(i = 2; i < 300; i++) {
  array = realloc(array, i * sizeof(int)); /* Reallocate the array */
  /* do stuff */
}
Hope this helps. Malloc and friends can be difficult to learn at first, but are /very/ useful once you get the hang of them
esus saves.... Passes to Moses, shoots, he scores!
Reply
#14
Well, some points ...

Quote:My coding style also differs slightly from Na_th_an's, I prefer to have the NULL test in the same block of code as the actual malloc/calloc

Me too, but I considered that being a newbie it would be more understandable to split the checking Smile

Quote:I also dont cast the return value of calloc because standard C doesnt require that you do and I use standard C complaint comments! (Glares at Na_th_an :evilSmile

When I code in Unix/Linux I do that, but in DOS/Windows I prefer the FAST // comments when I am not planning to make the code portable. About the casting... I'm a security freak Big GrinBig GrinBig Grin

Quote:I use fprintf(stderr, "..."); for portability reasons (Unix in particular distinguishes heavily between stdout and stderr.

Yeah, I should've done that :oops:

Quote:Another good point to pick up from Na_th_an's code is that he uses exit(-1); when there is an error, this allows any calling program to check the return value of the entire program to see if there was an error.

GCC (and its ports) rocks :king: ((Borland users, don't try this at home!!))

Just that Smile
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply
#15
I`m using a unix comp to writh C code on. I use gcc and I tryed to use man malloc but it only told me what it does not how to use it Sad
Reply
#16
Na_th_an, I was only joking about your coding style, I figured you probably knew all techniques I use. I think its good to point these things out to people who are new to C, because most existing C code looks like this and can be confusing at first. I prefer to run gcc with -ansi -Wall -pedantic whenever I can because it improves your coding style.

Shogun, the man pages do tell you how to use the functions, you just need to get used to reading them (Im not on a unix box at the moment so this is from memory ;-)). The man pages always give you the declaration of the function, which tells you alot:

Code:
$ man malloc

#include <stdlib.h>

Synopsis:
void *malloc(size_t bytes);

Description:
malloc allocates <bytes> bytes of memory and returns a pointer to the start of the block. If memory cannot be allocated then NULL is returned.

You need to include all the headers mention at the top of the man page. The synopsis tells you that malloc takes a single argument of type size_t. The size_t type implies that you should use the sizeof keyword for parameters. The return type is void *, which is similar to the AS ANY type in Qbasic.

The description gives you the rest of the information you need, it explains what the parameters do and what the return values are. The last sentence implies that you will need code such as:
Code:
int *array;

array = malloc(sizeof(int) * 10);

if(array == NULL) {
  fprintf(stderr, "Out of memory\n");
  exit(-1);
} else {
  /* Malloc worked */
}
Which tests the return value to see if the malloc worked. It takes a bit of practice but you can learn to use functions just from reading the man pages. For a bit of practice try reading and using the man pages for isupper, strcmp, strlen, sprintf, scanf, fopen, fread, and fclose. Remember to carefully read the function declaration, the description of parameters, and the possible return values.

If you are especially keen you can have a look at the headers that each man page tells you to include. On a unix system these are located in /usr/include. They can be tough going though, so dont worry if you can't understand them.

Na_th_an, did you know that the GNU C headers are now implementing functions such as printf as macros, I learnt about varidic macros recently when working with the system call interface in MINIX. For instance I have the following to mask system call names:
Code:
#define open(a, b, varargs...) _open(a, b, ##varargs)
Which masks all calls to open as _open (so users can declare things like int open; without causing clashes. The ## is a GNU extension to remove the trailing comma if varargs = 0. Pretty cool huh? 8)
esus saves.... Passes to Moses, shoots, he scores!
Reply
#17
Quote:Na_th_an, did you know that the GNU C headers are now implementing functions such as printf as macros, I learnt about varidic macros recently when working with the system call interface in MINIX. For instance I have the following to mask system call names:
Code:

#define open(a, b, varargs...) _open(a, b, ##varargs)


Which masks all calls to open as _open (so users can declare things like int open; without causing clashes. The ## is a GNU extension to remove the trailing comma if varargs = 0. Pretty cool huh?

Really cool. That will improve in efficence. I've been using simple macros for those ABS, SGN and the like functions, saving memory and time in calling a function. Another thing that I *really* like about 'c' are the inline functions. The preprocessor just sticks the code where the function is called. This rocks.

I should have been studied the MINIX source yet, but I am forever dropping the OS subject. I really like it and I feel that it is one of the most interesting things of computer science, but it is a hard subject in my plan (the old plan had a yearly subject, and now we have the same topics in about 4 months) and I am procastinating until I have more free time (say next year).

You will know now that the MINIX/Linux kernel makes extensive use of GOTOs Big GrinBig GrinBig Grin. GOTOs are cool sometimes, I'll kill some programming teachers out there.

See Dijkstra: GOTO considered harmful (1968)

See Frank Rubin: "GOTO considered harmful" considered harmful (1987) (it starts in the right bottom of the page).

Interesting Smile
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply
#18
why do you use fprintf instad of printf? isn´t fprintf for printing somthing from a file (I havn´t gotten to this part of my book yet just looked alittel at it and I understood that it did so, but I can be wrong)
Reply
#19
oh and why do you use void malloc doens´t that mean that malloc is always empty?
Reply
#20
1. printf writes on screen, you save a letter and a parameter Tongue

2. void does not mean "empty" that straight-forward. It is more like an absence of type. That's why I cast the returned value.
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)