http://groups.google.com/group/comp.lang.c?hl=en
Today's topics:
* A programming exercise - 7 messages, 6 authors
http://groups.google.com/group/comp.lang.c/t/15f027aef6f40479?hl=en
* So I want to exhaust a lot of memory - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.c/t/efd5686c57529f9b?hl=en
* pointer in front of a function ??? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/92eebf5162fe3d25?hl=en
* Interpreting command lines. - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/93328f341b8bc06b?hl=en
* Issue with printing a string - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c/t/26e268149fdbfe14?hl=en
* allocating m bytes dynamically - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c/t/3ce8c1090a941d64?hl=en
* Macro to manipulate chars inside string - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/9d5125687dd742c0?hl=en
* What is on topic here - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/a91a80117d377f7f?hl=en
* Warning to newbies - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/9597fd702985dff4?hl=en
==============================================================================
TOPIC: A programming exercise
http://groups.google.com/group/comp.lang.c/t/15f027aef6f40479?hl=en
==============================================================================
== 1 of 7 ==
Date: Thurs, Feb 4 2010 8:26 pm
From: lacos@ludens.elte.hu (Ersek, Laszlo)
In article <exercise-20100205050040@ram.dialup.fu-berlin.de>, ram@zedat.fu-berlin.de (Stefan Ram) writes:
> I have an idea for a program, yet I have not yet written and
> tested it.
>
> Here is an exercise that might be solved by this program:
>
> Write a C program to read positive int numbers from a
> user (a single int number is entered by its decimal
> digits and the enter key) which are terminated by entry
> of the digit 0 and the enter key, then allocate an array
> of exactly the required size and then store the numbers
> into this array (not including the terminating number 0).
>
> The program may only once allocate memory with allocated
> storage duration (malloc, calloc or so) (that is, for
> the array mentioned above), and it shall not contain any
> arbitrary limit for the number of numbers a user might
> enter, although limitations of the C implementation used
> might indeed impose a limitation on this number.
>
> I will post my own solution not before 2010-02-08T05:05:29+01:00,
> so feel free to post your own solution as a reply to this post.
Are you building a list on the stack via recursion?
Cheers,
lacos
== 2 of 7 ==
Date: Thurs, Feb 4 2010 8:59 pm
From: Kaz Kylheku
On 2010-02-05, Ben Pfaff <blp@cs.stanford.edu> wrote:
> ram@zedat.fu-berlin.de (Stefan Ram) writes:
>
>> Write a C program to read positive int numbers from a
>> user (a single int number is entered by its decimal
>> digits and the enter key) which are terminated by entry
>> of the digit 0 and the enter key, then allocate an array
>> of exactly the required size and then store the numbers
>> into this array (not including the terminating number 0).
>>
>> The program may only once allocate memory with allocated
>> storage duration (malloc, calloc or so) (that is, for
>> the array mentioned above), and it shall not contain any
>> arbitrary limit for the number of numbers a user might
>> enter, although limitations of the C implementation used
>> might indeed impose a limitation on this number.
>
> Recursion.
Temp file. :)
== 3 of 7 ==
Date: Thurs, Feb 4 2010 9:07 pm
From: pacman@kosh.dhis.org (Alan Curry)
In article <exercise-20100205050040@ram.dialup.fu-berlin.de>,
Stefan Ram <ram@zedat.fu-berlin.de> wrote:
| I have an idea for a program, yet I have not yet written and
| tested it.
|
| Here is an exercise that might be solved by this program:
|
| Write a C program to read positive int numbers from a
| user (a single int number is entered by its decimal
| digits and the enter key) which are terminated by entry
| of the digit 0 and the enter key, then allocate an array
| of exactly the required size and then store the numbers
| into this array (not including the terminating number 0).
|
| The program may only once allocate memory with allocated
| storage duration (malloc, calloc or so) (that is, for
| the array mentioned above), and it shall not contain any
| arbitrary limit for the number of numbers a user might
| enter, although limitations of the C implementation used
| might indeed impose a limitation on this number.
|
| I will post my own solution not before 2010-02-08T05:05:29+01:00,
| so feel free to post your own solution as a reply to this post.
|
#include <stdio.h>
#include <stdlib.h>
struct list {
struct list *next;
int n;
};
static int *read_numbers(struct list *list)
{
char buf[100];
int val, i, *ret;
struct list node, *p;
if(fgets(buf, sizeof buf, stdin)) {
if(sscanf(buf, "%d", &val)!=1) {
fprintf(stderr, "That's not a number\n");
exit(EXIT_FAILURE);
}
if(val!=0) {
node.n = val;
node.next = list;
return read_numbers(&node);
}
} else {
if(ferror(stdin)) {
perror("standard input");
exit(EXIT_FAILURE);
}
/* Naughty user sent EOF; pretend it was a 0 but with a warning */
fprintf(stderr, "Didn't get 0 terminator. List may be incomplete\n");
}
for(i=0,p=list;p;++i,p=p->next)
/*nothing*/;
ret = malloc(i * sizeof *ret);
if(!ret) {
perror("malloc");
exit(EXIT_FAILURE);
}
for(--i,p=list;p;--i,p=p->next)
ret[i] = p->n;
return ret;
}
int main(void)
{
int *numbers;
numbers = read_numbers(0);
/* do stuff with numbers[] I guess */
return 0;
}
Another option would be to pass the count as another parameter to the
recursive function. And it should probably also return the final count so you
can know how many numbers there are (the obvious solution of including the 0
terminator in the array was forbidden for some reason).
This is inferior to a realloc loop in at least 3 ways: the malloc overhead is
probably much less than the extra space taken up by saved registers in all
those stack frames, the total available stack space is probably smaller than
the total available malloc space, and there's no chance to do any cleanup
when the stack allocation finally fails, causing sudden death.
--
Alan Curry
== 4 of 7 ==
Date: Thurs, Feb 4 2010 9:26 pm
From: lacos@ludens.elte.hu (Ersek, Laszlo)
In article <Jsee0rKxJQ$d@ludens>, lacos@ludens.elte.hu (Ersek, Laszlo) writes:
> Are you building a list on the stack via recursion?
I mean a list represented by stack frames, not an explicitly linked
list.
----v----
#include <stdio.h>
#include <stdlib.h>
static long *
f(const size_t num)
{
long val, *arr;
scanf("%ld", &val);
arr = val ? f(num + 1u) : malloc(sizeof *arr * (num + 1u));
arr[num] = val;
return arr;
}
int
main(void)
{
long *p = f(0u),
val;
while ((val = *p++)) {
printf("%ld\n", val);
}
return 0;
}
----^----
(No error checking at all.)
Cheers,
lacos
== 5 of 7 ==
Date: Thurs, Feb 4 2010 11:40 pm
From: Phred Phungus
Alan Curry wrote:
> Another option would be to pass the count as another parameter to the
> recursive function. And it should probably also return the final count so you
> can know how many numbers there are (the obvious solution of including the 0
> terminator in the array was forbidden for some reason).
>
> This is inferior to a realloc loop in at least 3 ways: the malloc overhead is
> probably much less than the extra space taken up by saved registers in all
> those stack frames, the total available stack space is probably smaller than
> the total available malloc space, and there's no chance to do any cleanup
> when the stack allocation finally fails, causing sudden death.
>
I don't really understand the finer points there, but I did give source
a whirl:
dan@dan-desktop:~/source/unleashed/ch11$ gcc -D_GNU_SOURCE -Wall
-Wextra ac1.c -o out
dan@dan-desktop:~/source/unleashed/ch11$ ./out
^C
dan@dan-desktop:~/source/unleashed/ch11$ ./out
3 4 5
That's not a number
dan@dan-desktop:~/source/unleashed/ch11$
dan@dan-desktop:~/source/unleashed/ch11$ ./out
345
That's not a number
dan@dan-desktop:~/source/unleashed/ch11$ cat ac1.c
#include <stdio.h>
#include <stdlib.h>
struct list {
struct list *next;
int n;
};
static int *read_numbers(struct list *list)
{
char buf[100];
int val, i, *ret;
struct list node, *p;
if(fgets(buf, sizeof buf, stdin)) {
if(sscanf(buf, "%d", &val)!=1) {
fprintf(stderr, "That's not a number\n");
exit(EXIT_FAILURE);
}
if(val!=0) {
node.n = val;
node.next = list;
return read_numbers(&node);
}
} else {
if(ferror(stdin)) {
perror("standard input");
exit(EXIT_FAILURE);
}
/* Naughty user sent EOF; pretend it was a 0 but with a warning */
fprintf(stderr, "Didn't get 0 terminator. List may be incomplete\n");
}
for(i=0,p=list;p;++i,p=p->next)
/*nothing*/;
ret = malloc(i * sizeof *ret);
if(!ret) {
perror("malloc");
exit(EXIT_FAILURE);
}
for(--i,p=list;p;--i,p=p->next)
ret[i] = p->n;
return ret;
}
int main(void)
{
int *numbers;
numbers = read_numbers(0);
/* do stuff with numbers[] I guess */
return 0;
}
// gcc -D_GNU_SOURCE -Wall -Wextra ac1.c -o out
dan@dan-desktop:~/source/unleashed/ch11$
I don't mind saying that I want to win the Stefen Ram Ramstein. Maybe
we could collude in small groups. Gruss,
--
== 6 of 7 ==
Date: Thurs, Feb 4 2010 11:49 pm
From: Phil Carmody
ram@zedat.fu-berlin.de (Stefan Ram) writes:
> I have an idea for a program, yet I have not yet written and
> tested it.
>
> Here is an exercise that might be solved by this program:
>
> Write a C program to read positive int numbers from a
> user (a single int number is entered by its decimal
> digits and the enter key) which are terminated by entry
> of the digit 0 and the enter key, then allocate an array
> of exactly the required size and then store the numbers
> into this array (not including the terminating number 0).
>
> The program may only once allocate memory with allocated
> storage duration (malloc, calloc or so) (that is, for
> the array mentioned above), and it shall not contain any
> arbitrary limit for the number of numbers a user might
> enter, although limitations of the C implementation used
> might indeed impose a limitation on this number.
>
> I will post my own solution not before 2010-02-08T05:05:29+01:00,
> so feel free to post your own solution as a reply to this post.
Acording to the as-if rule, the following should be allowed:
int main() { return 0; }
However, I suspect you're more looking for something like this:
#include <stdio.h>
#include <stdlib.h>
static int n,l;
static int*r;
void rn(void)
{
int i;
scanf("%d",&i)&&i?n++,l++,rn(),r&&(r[--n]=i):l?!(r=malloc(l*sizeof(*r))):0;
}
int main()
{
rn();
/* This bit not actually asked for */
if(r) for(n=0; n<l; ++n) printf("%i\n",r[n]);
return !l;
}
I've minimised local variable usage to the absolute minimum, in order
to try and keep the recursive part as wastefree as possible, and thus
permit deeper recursion and a larger array given a limited quantity of
RAM. Of course, just the housekeeping of doing the rest of the task
imposes a lower limit on how tight that can be.
For even tighter RAM use on a typical architecture, replace
scanf("%d",&i)&&i
with
gets(buf)&&(i=atoi(buf))
Phil
--
Any true emperor never needs to wear clothes. -- Devany on r.a.s.f1
== 7 of 7 ==
Date: Fri, Feb 5 2010 12:00 am
From: Michael Tsang
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Stefan Ram wrote:
> I have an idea for a program, yet I have not yet written and
> tested it.
>
> Here is an exercise that might be solved by this program:
>
> Write a C program to read positive int numbers from a
> user (a single int number is entered by its decimal
> digits and the enter key) which are terminated by entry
> of the digit 0 and the enter key, then allocate an array
> of exactly the required size and then store the numbers
> into this array (not including the terminating number 0).
>
> The program may only once allocate memory with allocated
> storage duration (malloc, calloc or so) (that is, for
> the array mentioned above), and it shall not contain any
> arbitrary limit for the number of numbers a user might
> enter, although limitations of the C implementation used
> might indeed impose a limitation on this number.
>
> I will post my own solution not before 2010-02-08T05:05:29+01:00,
> so feel free to post your own solution as a reply to this post.
#include <stdio.h>
#include <stdlib.h>
//! Read a list of unsigned integers from the standard input and return an
// array of them.
/*! @param[out] size A pointer to a size_t object to put the size of the
* allocated array in. If it is a null pointer, the size is discarded.
* @return The dynamically allocated array containing the numbers read.
*/
unsigned *get_numbers(size_t *size) {
static size_t level;
unsigned number;
scanf("%u", &number);
if(!number) {
if(size) {
*size = level;
}
return malloc(level * sizeof (unsigned));
} else {
++level;
unsigned *array = get_numbers(size);
--level;
array[level] = number;
return array;
}
}
int main(void) {
size_t size;
unsigned *array = get_numbers(&size);
for(unsigned *p = array; p != array + size; ++p) {
printf("%u\n", *p);
}
}
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEARECAAYFAktr0C0ACgkQm4klUUKw07Cr7gCfbspoJ4/2UIaCS0gS8vHUSQXj
VcQAnRg0omQys/sYLh6v8N2RQeB1Fdrk
=lLr0
-----END PGP SIGNATURE-----
==============================================================================
TOPIC: So I want to exhaust a lot of memory
http://groups.google.com/group/comp.lang.c/t/efd5686c57529f9b?hl=en
==============================================================================
== 1 of 3 ==
Date: Thurs, Feb 4 2010 8:48 pm
From: ImpalerCore
On Feb 4, 5:50 pm, ImpalerCore <jadil...@gmail.com> wrote:
> What is the best way to exhaust a lot of memory but at the same time
> leave enough so that I can test out of memory errors for some
> container functions, i.e. like not having enough memory to allocate a
> new list node.
>
> So far, all I've done is something like:
>
> const size_t block_size = 1024*1024;
> size_t count;
>
> for ( count = 0; malloc( block_size ); ++count );
> ...
>
> The smaller the block_size, the longer it takes to exhaust memory. So
> I plan to starting with a large block size, exhausting memory,
> reducing the block size, exhausting memory, until I get down to a
> level that I can exercise my out of memory error handling.
>
> Is this a good strategy? Are there pitfalls that I'm not seeing?
> Again, I'm assuming that ending the process reclaims the memory used.
Thanks for all the responses. I have been using DMALLOC for general
memory leak detection, it seems to work well for me, but I can't seem
to make it work when I try to exercise actual out of memory problems.
I'll look at the suggestions and see what I can do to make a special
allocator/malloc that puts an upper limit the amount of memory
available.
Best regards,
John D.
== 2 of 3 ==
Date: Thurs, Feb 4 2010 10:59 pm
From: Phil Carmody
Ian Collins <ian-news@hotmail.com> writes:
> ImpalerCore wrote:
>> What is the best way to exhaust a lot of memory but at the same time
>> leave enough so that I can test out of memory errors for some
>> container functions, i.e. like not having enough memory to allocate a
>> new list node.
>
> Use your own mock malloc. Tat way you can return what ever you like,
> including NULL.
Looks like librandomcrash has some potential customers...
Phil
--
Any true emperor never needs to wear clothes. -- Devany on r.a.s.f1
== 3 of 3 ==
Date: Thurs, Feb 4 2010 11:22 pm
From: Ian Collins
Ersek, Laszlo wrote:
> In article <7t11vpFqmjU3@mid.individual.net>, Ian Collins <ian-news@hotmail.com> writes:
>> ImpalerCore wrote:
>>> What is the best way to exhaust a lot of memory but at the same time
>>> leave enough so that I can test out of memory errors for some
>>> container functions, i.e. like not having enough memory to allocate a
>>> new list node.
>> Use your own mock malloc. Tat way you can return what ever you like,
>> including NULL.
>
> Yes. Make your container's constructor(s) take an allocator, for
> example:
That's a bit over the top, I was suggesting defining malloc and free in
the test code.
--
Ian Collins
==============================================================================
TOPIC: pointer in front of a function ???
http://groups.google.com/group/comp.lang.c/t/92eebf5162fe3d25?hl=en
==============================================================================
== 1 of 1 ==
Date: Thurs, Feb 4 2010 8:59 pm
From: Barry Schwarz
On Wed, 3 Feb 2010 21:04:58 -0800 (PST), 2005 <FW3006@sbcglobal.net>
wrote:
>On Feb 3, 8:34�pm, Andrew Poelstra <apoels...@localhost.localdomain>
>wrote:
>> On 2010-02-04, 2005 <FW3...@sbcglobal.net> wrote:
>>
>> > 1) What is the big deal about * in front of RandStr ? �- I guess it
>> > means pointer to function - but what are the benefits?
>>
>> Nope - it means that instead of returning a char, you're
>> returning a pointer to char. A very different beast.
>>
>> > 2) If I call the RandStr in main or another function, would
>> > char str[6];
>> > str = RandStr
Without the mandatory () empty argument list, this is not even a
function call.
>> > work? �Why not?
>>
>> No, because you can't assign to arrays directly like that. There
>> was another thread about exactly this earlier today; see if you
>> can find it on groups.google.com or something.
>>
>> > char *RandStr(void)
>> > {
>> > � � � � int i;
>> > � � � � char RandStr[5];
>>
>> Here you use the same name for a char[5] as you do for the function.
>> this is legal and won't cause any trouble as long as you don't use
>> any recursion. But it's terrible style and will confuse people who
>> are reading the code.
>>
>> > � � � � for(i = 0; i <= 5; i++)
>> > � � � � {
>> > � � � � � � � �RandStr[i] = rand() % 78;
>>
>> This won't give you printable characters on any charset I've used.
>> (Well, /some/ will be printable. Maybe. Others will be print control
>> characters and beeps. Maybe.)
>>
>> Consider using the RandStr() I gave you in the other thread.
>>
>> > � � � � }
>> > � � � � return RandStr;
>> > }
>>
>> Yikes! You can't do this because RandStr[] was allocated locally
>> in your function - so when you return, RandStr[] dies. And you
>> return a pointer to it, which if used, will result in Undefined
>> Behavior.
>>
>> If you allocated RandStr with malloc() (including <stdlib.h>!)
>> or passed it into the function, it would keep on living after
>> the function returns, and you'd be safe.
>>
>> But remember to free() anything you get with malloc(), or you'll
>> have a memory leak on your hands.
>
>1) Are u saying if "return RandStr" is deleted, then RandStr[] will
>not die?
Using the same name for a function and an array just makes the
conversation unnecessarily confusing.
The array is an automatic array local to the function. It comes into
being when the function is called and ceases to exist when the
function exits. Returning or not returning its address does not
affect its lifespan at all. The point being made was that once the
array dies, its address no longer has any meaning and attempting to
use it for any purpose invokes undefined behavior.
But if you delete the return statement, you have the equally obnoxious
mistake of not returning a value from a function defined to return
one. Any attempt to use the return value in the calling function when
the function didn't actually return one invokes undefined behavior.
>2) Thanks for the malloc recommendation - should it be in the main()
>or as a global/static variable or inside the char *RandStr(void) ?
Why did you interject a completely unrelated issue such as global
variables?
If you call malloc in main, you will need to pass the resulting
address to your function. If you call malloc in the function, you
will need to return the resulting address to the caller and let that
function free it when it is no longer needed.
--
Remove del for email
==============================================================================
TOPIC: Interpreting command lines.
http://groups.google.com/group/comp.lang.c/t/93328f341b8bc06b?hl=en
==============================================================================
== 1 of 1 ==
Date: Thurs, Feb 4 2010 10:42 pm
From: Phred Phungus
Ben Bacarisse wrote:
> [re-ordered for convenience]
> Phred Phungus <Phred@example.invalid> writes:
>> frank wrote:
> <snip>
>> #include <stdio.h>
>>
>> int z; /* definition: storage is reserved */
>> extern int y; /* declaration: just a promise of existence */
>> extern int x = 6; /* definition: by giving it a value, you force the
>> compiler to take it as a definition rather than a mere declaration */
> <snip>
>
>>> Is z guaranteed to be zero?
>
> In this case, yes. You might think that z is zero because of
> 6.7.8 p10 that gives the initial value of objects that are not
> explicitly initialised, but that is technically not so.
If an object that has automatic storage duration is not initialized
explicitly, its value is
indeterminate. If an object that has static storage duration is not
initialized explicitly,
then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned)
zero;
— if it is an aggregate, every member is initialized (recursively)
according to these rules;
— if it is a union, the first named member is initialized (recursively)
according to these
rules.
>
> int z; (at file scope) is not an external definition. It is a
> tentative definition and, if there is no external definition for that
> identifier in the translation unit, the behaviour is as if an explicit
> initialiser of 0 had been written. I.e. the initial value is given by
> section 6.9.2 p2 with some more technical details about the composite
> type.
>
> The upshot is that you don't know the value until the end of the
> translation unit since there may be a subsequent int z = 42; which is
> not an error as it would be if both were in the same block scope.
I'm not quite following you yet, Ben. Do I understand correctly that
while the value of z is indeterminate at onset of execution, by the time
it gets to my printf it must, as an arithmetic type, be zero?
--
Phred
==============================================================================
TOPIC: Issue with printing a string
http://groups.google.com/group/comp.lang.c/t/26e268149fdbfe14?hl=en
==============================================================================
== 1 of 2 ==
Date: Thurs, Feb 4 2010 11:06 pm
From: Michael Foukarakis
On Feb 4, 10:13 pm, "Default User" <defaultuse...@yahoo.com> wrote:
> Michael Foukarakis wrote:
> > On Feb 4, 2:54 pm, Richard Heathfield <r...@see.sig.invalid> wrote:
> > > Michael Foukarakis wrote:
> > > > On Feb 4, 12:08 pm, Richard Heathfield <r...@see.sig.invalid>
> > > > wrote:
> > > >> Michael Foukarakis wrote:
> > > > Indeed. Discussions also need arguments;
>
> > > <sigh> Not so's you'd notice.
>
> > Worth putting effort into, nonetheless. Trolls get tired, grow up, or
> > die, eventually.
>
> They get tired much faster if you ignore them.
And miss all the fun? :'(
== 2 of 2 ==
Date: Thurs, Feb 4 2010 11:07 pm
From: Phil Carmody
Nobody <nobody@nowhere.com> writes:
> On Thu, 04 Feb 2010 23:09:18 +0200, Phil Carmody wrote:
>
>> I mention in passing that gcc (4.1 here), even with no
>> optimisation, turns strlen(src) into a constant.
>
> Are you quite sure it's gcc?
No. I just hammered randomly on the keys and ran a random program
instead of the compiler. Looking at my command-line history, it
appears I ran 'rm' instead, so I can't even tell you what code
it actually was 'compiling'.
> glibc's <string.h> includes <bits/string.h>, which has a whole host of
> macros and inline asm. The actual strcpy() macro is:
>
> #define strcpy(dest, src) \
> (__extension__ (__builtin_constant_p (src) \
> ? (sizeof ((src)[0]) == 1 && strlen (src) + 1 <= 8 \
> ? __strcpy_a_small ((dest), (src), strlen (src) + 1) \
> : (char *) memcpy ((char *) (dest), \
> (__const char *) (src), \
> strlen (src) + 1)) \
> : __strcpy_g ((dest), (src))))
>
> Try the test again with "#undef strcpy".
Nice hatstand, Roger.
Phil
--
Any true emperor never needs to wear clothes. -- Devany on r.a.s.f1
==============================================================================
TOPIC: allocating m bytes dynamically
http://groups.google.com/group/comp.lang.c/t/3ce8c1090a941d64?hl=en
==============================================================================
== 1 of 2 ==
Date: Thurs, Feb 4 2010 11:06 pm
From: santosh
2005 wrote:
> On Feb 4, 1:43 am, Richard Heathfield <r...@see.sig.invalid> wrote:
> > 2005 wrote:
> > > 1) If I want to allocate m bytes dynamically would the following do?
> >
> > #include <stdlib.h>
> >
> > #define MAX 100
> >
> > int main(void)
> > {
> > size_t num_ints = MAX;
> > int *ptr = malloc(m * sizeof *ptr);
> > if(ptr != NULL)
> > {
> > int i = 0;
> > while(i < MAX)
> > {
> > ptr[i] = i;
> > }
> > /* use those values in other ways
> > if you like, and then, when you
> > have finished, call free():
> > */
> > free(ptr);
> > }
> > return 0;
> >
> > }
> >
> > To answer your question, yes, the above will do nicely.
> >
> > > 2) What is the purpose of the for loop here - assign initial value?
> >
> > In your code, the purpose appears to have been to break your program.
> > (It reassigns ptr, then tries to pass that new value to free(), which
> > invokes undefined behaviour, as does the call to malloc - the compiler
> > would have warned you about this if you hadn't hobbled it with a cast).
> >
> > In the above code, however, the purpose is to assign initial values to
> > the ints allocated by malloc.
> Thank you Richard and everyone;
>
> 1) Am I correct "free(ptr);" could have been placed after the
> bracket ?
Which bracket?
In general you can free() a pointer value anytime after it has been
returned by malloc() and friends. But it must be the same value. You
can't modify the value, as you did above, and attempt to free() it. If
you do need to modify, save a copy of the original.
Also, though the storage returned by malloc() and co. will persist
throughout the life of the program, you should keep in mind the
lifetime of the pointer object(s) used to reference the storage, which
might be function scope or block scope.
> 2) I put a "printf ("ptr[%d] = %d\n", i, ptr[i]);" after "ptr[i] = i"
> - it printed the following - ie from 1 to 5959:
>
> 1 ptr[0] = 0
> 2 ptr[0] = 0
> 3 ptr[0] = 0
> .......
> 5956 ptr[0] = 0
> 5957 ptr[0] = 0
> 5958 ptr[0] = // it did not print a value for "i"
> 5959 Timeout
>
> Why "5959"? Why "Timeout" ? Irrespective of what value MAX is
> assigned, it does this! I ran it on codepad.org
Yes, well you assign MAX to num_ints but never use that object. You
instead supply 'm' to malloc(). Where does 'm' come from and what
value does it contain? Are you sure you don't want:
int *ptr = malloc(num_ints * sizeof *ptr);
Also in your loop as given above, 'i' won't magically increment itself
until MAX. You'll have to do so manually. That is why you get the
above output, since 'i' stays at zero.
== 2 of 2 ==
Date: Fri, Feb 5 2010 12:02 am
From: Richard Heathfield
Mark wrote:
> Richard Heathfield wrote:
>> #define MAX 100
>>
>> int main(void)
>> {
>> size_t num_ints = MAX;
>> int *ptr = malloc(m * sizeof *ptr);
> I guess it should've been:
>
> int *ptr = malloc(num_ints * sizeof *ptr);
Um, yes. Thanks for the correction.
You'd think shorter posts would be easier to get right, wouldn't you? Oh
well.
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
==============================================================================
TOPIC: Macro to manipulate chars inside string
http://groups.google.com/group/comp.lang.c/t/9d5125687dd742c0?hl=en
==============================================================================
== 1 of 1 ==
Date: Thurs, Feb 4 2010 11:43 pm
From: Michael Tsang
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Andre wrote:
> I need a macro to transform an value like 274A into {(char)0x27, (char)
> 0x4A}. Does anyone know how to do it, or where can I find more
> information about this kind of macro?
Don't use macros. They are dangerous. Use inline functions instead.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEARECAAYFAktrzCwACgkQm4klUUKw07ClwwCdHm+RyWuiDPcH+6Xp/Rs+bhNB
dn8AniI/07Z9gcywUG/LKEejzS+lfeEA
=X+DB
-----END PGP SIGNATURE-----
==============================================================================
TOPIC: What is on topic here
http://groups.google.com/group/comp.lang.c/t/a91a80117d377f7f?hl=en
==============================================================================
== 1 of 1 ==
Date: Thurs, Feb 4 2010 11:57 pm
From: Richard Heathfield
Kaz Kylheku wrote:
> On 2010-02-04, Richard Heathfield <rjh@see.sig.invalid> wrote:
>> If you want to raise the S/N ratio in clc, you can do it far more
>> effectively by boosting the signal than by adding to the noise.
>
> Surely you mean by /reducing/ the noise?
No, I meant what I said.
(S + d) / N > S / (N + d)
where S, N, d are all greater than 0.
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
==============================================================================
TOPIC: Warning to newbies
http://groups.google.com/group/comp.lang.c/t/9597fd702985dff4?hl=en
==============================================================================
== 1 of 1 ==
Date: Fri, Feb 5 2010 12:04 am
From: spinoza1111
On Feb 5, 1:59 am, Seebs <usenet-nos...@seebs.net> wrote:
> On 2010-02-04, Nick Keighley <nick_keighley_nos...@hotmail.com> wrote:
>
> > On 3 Feb, 16:27,spinoza1111<spinoza1...@yahoo.com> wrote:
> >> Can't you just let Moore's Law handle "efficiency"?
> > interesting question.
>
> It is.
>
> FWIW: You can't.
>
> First off, Moore's Law doesn't expand as fast as some particularly
> expensive operations do. Secondly, even if it does expand with the right
> big-O relation, it may not expand fast enough to do much good. Thirdly,
You should stay out of this conversation, since that's what
"killfiling" means.
Furthermore, your comment is nonsense, and I don't think you
understand computational complexity, for if "it" expands with "the
right big O relation", then it follows that this is fast
enough...although in fact, we shouldn't rely on Moore's Law to justify
the use of mathematically slow algorithms, and that was not implied by
the original post. We weren't discussing buying faster computers so as
to code bubble sort, we were discussing running effective algorithms
faster. You seem to me unqualified to join this conversation, since
like many programmers educated only on the job, you're applying an
oversimplified and normative picture to a science.
You read in the Awesome Computer Journal of Awesome Computers about
computational complexity, and decided that anyone who doesn't strike
the appropriate corporate pose, required for employability, is a Bad
person, because he's not Awesome; for less than Awesomeness is
unacceptable given the inner contour everyone's secret wound. Thus,
Chris T could not have been a real professional talking about a real
problem as opposed to someone finding bugs and writing scripts,
therefore you're trying to distort the conversation into your defense
of Awesome Computing and caricature people who you don't understand or
like as people who would defend something other than Awesome
Computing.
Get a life.
> a whole lot of devices have issues like "battery life" to think about,
> such that reducing CPU usage is still a very valuable endeavor.
>
> In short, no matter how fast your CPUs are, 20% is still 20%.
True overall. But not what is under discussion, and you don't belong
here if you've killfiled people in the discussion.
>
> > we might be sad if it happens at an inappropriate moment!
>
> Any World of Warcraft player can tell you how much that can matter!
Computer games and TV ("Baldrick") debase grownup discussions IMO.
>
> Well, anyone who played back in the day...
>
> > I believe
> > modern garbage collectors are less "lumpy" than the old mark-and-sweep
> > ones. Perhaps another example of where efficiency matters!
>
> Yes.
>
> And even if it's less efficient in absolute CPU cycles, it's useful for
> the certainty that you won't suddenly get a three-second lag in combat.
(Sigh). (Eye roll). (Crotch grab). (Panto-mime of shooting oneself in
the head including mime of the exit spray of blood and brains, an
important part of any proper Panto-mime of this action).
>
> > compilers aren't usually classified as real time.
>
> I think that was his point, but I can't honestly say.
Blow me.
>
> >> I understand that
> >> absolute performance goals may apply. I do object to treating
> >> performance speed as an unalloyed good when the customer doesn't ask
> >> for it.
> > quite right. On the other hand he may not *ask* for it and still
> > expect it. "You never told me it would take an hour to reload the
> > system!"
>
> I cannot suggest a circumstance in which it would NOT be an unalloyed good,
> all else being equal. Which it might not be.
>
> -s
> --
> Copyright 2010, all wrongs reversed. Peter Seebach / usenet-nos...@seebs.nethttp://www.seebs.net/log/<-- lawsuits, religion, and funny pictureshttp://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
==============================================================================
You received this message because you are subscribed to the Google Groups "comp.lang.c"
group.
To post to this group, visit http://groups.google.com/group/comp.lang.c?hl=en
To unsubscribe from this group, send email to comp.lang.c+unsubscribe@googlegroups.com
To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.c/subscribe?hl=en
To report abuse, send email explaining the problem to abuse@googlegroups.com
==============================================================================
Google Groups: http://groups.google.com/?hl=en
No comments:
Post a Comment