This one time, at band camp, O Plameras wrote:
>Benno wrote:
>
>>On Tue Nov 22, 2005 at 16:16:29 +1100, O Plameras wrote:
>> 
>>
>>>Hi ashley,
>>>
>>>I have three sets of codes that will do the task as I see it from your 
>>>codes.
>>>I presented these three codes from the least to the most preferred coding.
>>>
>>>The common idea in all the three codes: 'somefunction' has static array
>>>of characters that is to be printed in 'main'; to accomplish this, just 
>>>pass that address of the
>>>first character in a string to be printed. I changed the TYPE of
>>>'somefunction' from 'int' to 'char *' to achieve this end.
>>>
>>>I used malloc instead of calloc in Coding 2. It is sufficient in the 
>>>context of your original codes.
>>>
>>>Notice I did not use calloc or malloc in Coding 3 as I am just passing 
>>>an address.
>>>
>>>Coding 1.  
>>>#include <stdio.h>
>>>#include <stdlib.h>
>>>#include <string.h>
>>>char *
>>>somefunction()
>>>{
>>>     char *string1;
>>>     char *string2 = "some words\0";
>>>     string1 = (char *)calloc(strlen(string2 + 1), sizeof (char));
>>>   
>>>
>>
>>Should be strlen(string2) + 1
>>
>> 
>>
>
>Your are wrong. The string is "some words\0". there is no need for extra 
>char.

How do you think strlen() works?

Also, it's pretty clear you were writing this anyway, but typoed the
placement of the closing parenthesis.

>Your are wrong. The string is "some words\0". there is no need for extra 
>char.

Your jedi mind tricks do not work on me!

>>Moral of the story is don't code in C ;) Or if you do use as many tools
>>to help you as possible. -Wall, and a C linter are a good start.
>>Valgrind is also meant to be good, although I haven't
>>used it.
>> 
>>
>
>I don't understand this. Please explain.

Benno's talking about the buffer overruns caused by the incorrect pointer
arithmetic in your examples.  You can track them down with "as many tools to
help you as possible", e.g. gcc -Wall, valgrind.

Or use pascal where the length of a string isn't determined by the position
of the null :)
-- 
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to