Cant see why malloc() req'd. 
Author Message
 Cant see why malloc() req'd.

: Instead of running it dumps core. To my mind I dont have to
: allocate memory for template.string in main() because string
: is already initialised to a bunch of spaces in template.

It sounds like you are thinking of a pointer as a type of variable
which can store data.   I know that I used to have the same view and
it caused me nothing but confusion and trouble.  Pointers really don't
work like that.  In your code you have a pointer pointing to a bunch
of spaces.  This doesn't mean you have assigned the pointer to point
at some "space" to which data may be written. Even if your reasoning
was correct, how would you deal with the situation where the string you
want to copy is longer than the number of spaces you have "initialized"?
When you initialize a pointer in manner in which you have, the memory
address pointed to is read only (as your SIGSEGV has pointed out to you).

When you malloc() some memory, the address of the memory is returned
by malloc().  Normally one assigned that returned address to a pointer.
Although you can now write and read data to and from this chunk of memory,
don't think of the pointer as a variable.    The pointer only points to
the memory.  If you have a situation like this:

char *ptr,
     array[80];

     ptr = malloc(10);  /* omit error checking for brevity */
     strcpy( ptr, "some data" );

     ptr = array;  /* opps! the memory which was pointed to by ptr is still
                    * allocated, however there is no way to access it
                    * because there is now no pointer pointing  to it.
                    * Drats!
                    */

Good Luck,

Paul

--

Director, X-ray Structural Facility |   phone: (919) 515-7362
Department of Chemistry - Box 8204  |   FAX:   (919) 515-5079
North Carolina State University     |
Raleigh, NC, 27695-8204
http://www.*-*-*.com/



Tue, 08 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.
: Hi there
: I have a program that should take a string on the command
: line and print it literally as well as in UPPERCASE. eg
: %structst1 name
: Here's the string name.
: Here's the upstring NAME.

: Instead of running it dumps core. To my mind I dont have to
: allocate memory for template.string in main() because string
: is already initialised to a bunch of spaces in template.
: My testing has shown that I -do- however need to alloc mem
: in change() for upstring??? I dont understand - seems to me
: that upstring too is initialised to a bunch of spaces. Even
: if *copy is a new pointer to the struct template upstring is
: still referenced back to the empty upstring in the struct??

: Someone please explain why I need to alloc mem in change()?
: Any help much appreciated.

: Dave

: /* structst1.c - learning about pointers to structs */
: #include <stdio.h>
: #include <string.h>

: #define MAX 80

: struct buf {
:       char *string;
:       char *upstring;
: };

: struct buf template = {
:       /* string points to */  "              ",
:       /* upstring points to */"              ",
: };  

Why do you need the comma after the second string?

: void change(struct buf *copy);
: int main(int argc, char *argv[])
: {
:       struct buf template;

Is not "template" declared and initialized as global variable?

:       strcpy(template.string,argv[1]);

:       printf("Here's the string %s.\n",template.string);
:      
:       change(&template);

:       printf("Here's the upstring %s.\n",template.upstring);

: return 0;
: }

: /* function to convert lower to upper case */
: void change(struct buf *copy)
: {
:       int i = 0;
:       int ch;
:      
:       for(i = 0; i < strlen(copy->string); i++)
:         {      
:           ch = copy->string[i];
:           ch -= 32;
:           copy->upstring[i] = ch;
:         }
: }

You can use this format:

       for(i=0; copy->string[i] != '\0'; i++)
          copy->upstring[i] = copy->string[i]-32;

       copy->upstring[i] = '\0';       /* terminate the string */

I think the main problem is that you defined a "struct buf template"
in the main function which hidden the global "template". And the
local "template" has not been intialized (no memory for the two
pointers). So you will get error when you run the program.

Following testing program works on my SGI IRIX6.5.
But be careful, I think your string should never
be longer than the space you reservered in the template.

#include <stdio.h>
#include <strings.h>

struct x {
        char *s1;
        char *s2;

Quote:
};

struct x template = {"          ", "          "};

int main(void)
{
  sprintf(template.s1, "String 1\n");
  strcpy(template.s2, "string 2\n");

  printf("%s\n", template.s1);
  printf("%s\n", template.s2);

  return 1;

Quote:
}



Tue, 08 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.
A couple of things to watch out for.

Quote:
>struct buf {
>    char *string;
>    char *upstring;
>};

This defines your structure as two pointer-to-char.

Quote:
>struct buf template = {
>    /* string points to */  "              ",
>    /* upstring points to */"              ",
>};  

The last comma is wrong.  Also note that over-writing string literals may not be
possible, or at least can be dangerous.  A compiler is free to keep a single
copy of duplicate string literals - changing one will change all.  A compiler is
also free to make string literals const - so that writing to them core dumps.

Quote:
>void change(struct buf *copy);
>int main(int argc, char *argv[])
>{
>    struct buf template;

This declaration hides the global one above.  This 'template' is uninitialized
and its pointers are garbage that do not point at allocated memory - except by
chance.  That's why it dies here:

Quote:
>    strcpy(template.string,argv[1]);

--
#include <standard.disclaimer>
 _
Kevin D Quitt  USA 91351-4454           96.37% of all statistics are made up
Per the FCA, this email address may not be added to any commercial mail list


Tue, 08 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.


Quote:
> A couple of things to watch out for.

> >struct buf {
> >       char *string;
> >       char *upstring;
> >};

> This defines your structure as two pointer-to-char.

> >struct buf template = {
> >       /* string points to */  "              ",
> >       /* upstring points to */"              ",
> >};  

> The last comma is wrong.

I'm not so sure. You might be right, but I seem to recall (I just had a
good solid trawl through C9X but came up no-trumps) that K&R specifically
allows a trailing comma in an initialiser list of this kind to make it
easier to automatically generate code, or some similar reason. BICBW.

Quote:
> Also note that over-writing string literals may not be
> possible, or at least can be dangerous.

Quite right.

<snip>



Tue, 08 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.
Hi there
I have a program that should take a string on the command
line and print it literally as well as in UPPERCASE. eg
%structst1 name
Here's the string name.
Here's the upstring NAME.

Instead of running it dumps core. To my mind I dont have to
allocate memory for template.string in main() because string
is already initialised to a bunch of spaces in template.
My testing has shown that I -do- however need to alloc mem
in change() for upstring??? I dont understand - seems to me
that upstring too is initialised to a bunch of spaces. Even
if *copy is a new pointer to the struct template upstring is
still referenced back to the empty upstring in the struct??

Someone please explain why I need to alloc mem in change()?
Any help much appreciated.

Dave

/* structst1.c - learning about pointers to structs */
#include <stdio.h>
#include <string.h>

#define MAX 80

struct buf {
        char *string;
        char *upstring;

Quote:
};

struct buf template = {
        /* string points to */  "              ",
        /* upstring points to */"              ",

Quote:
};  

void change(struct buf *copy);
int main(int argc, char *argv[])
{
        struct buf template;

        strcpy(template.string,argv[1]);

        printf("Here's the string %s.\n",template.string);

        change(&template);

        printf("Here's the upstring %s.\n",template.upstring);

return 0;

Quote:
}

/* function to convert lower to upper case */
void change(struct buf *copy)
{
        int i = 0;
        int ch;

        for(i = 0; i < strlen(copy->string); i++)
          {      
            ch = copy->string[i];
            ch -= 32;
            copy->upstring[i] = ch;
          }

Quote:
}



Wed, 09 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.
On 23 Jul 1999 21:20:58 +0100, "Richard Heathfield"

I am a bit concerned I dont see any sign of Kevins
posting in this thread. I have scanned over the
downloaded headers and cant seem to see any
postings from him - anybody have any ideas?
Thanks to those for whos postings I have been
able to read, they have been very helpful and I
will give them yet more attention.

Dave



Wed, 09 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.


Quote:
> On 23 Jul 1999 21:20:58 +0100, "Richard Heathfield"



> I am a bit concerned I dont see any sign of Kevins
> posting in this thread. I have scanned over the
> downloaded headers and cant seem to see any
> postings from him - anybody have any ideas?

I have sent a brief explanation of the randomness of Usenet article arrival
times, and a full copy of Kevin's posting, to David via email.

So, if you had the same idea, please refrain or the poor lad'll be swamped
by 'helpful' email. :-(

--
Richard Heathfield

The bug stops here.



Wed, 09 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.


Quote:
>A couple of things to watch out for.

>>struct buf {
>>       char *string;
>>       char *upstring;
>>};

>This defines your structure as two pointer-to-char.

>>struct buf template = {
>>       /* string points to */  "              ",
>>       /* upstring points to */"              ",
>>};  

>The last comma is wrong.

It is correct although you could argue whether it is good style or not.
If you look at the syntax for an initialization

initializer:
        assignment-expression
        { initializer-list }
        { initializer-list , }

initializer-list:
        initializer
        initializer-list , initializer

it makes specific allowance for a , just before a }

Quote:
>Also note that over-writing string literals may not be
>possible, or at least can be dangerous.  A compiler is free to keep a single
>copy of duplicate string literals - changing one will change all.  A compiler is
>also free to make string literals const - so that writing to them core dumps.

I recommend that you make your line length slightly less than 80
characters so it all remains visible on 80 character screens after
being quoted at least one or two levels.

--
-----------------------------------------


-----------------------------------------



Wed, 09 Jan 2002 03:00:00 GMT  
 Cant see why malloc() req'd.


Quote:
>I recommend that you make your line length slightly less than 80

Had it set that way but reinstalled the newsreader and missed that.
Thanks for pointing it out.

--
#include <standard.disclaimer>
 _
Kevin D Quitt  USA 91351-4454           96.37% of all statistics are made up
Per the FCA, this email address may not be added to any commercial mail list



Thu, 10 Jan 2002 03:00:00 GMT  
 
 [ 9 post ] 

 Relevant Pages 

1. why my Control methods can't be seen by outside

2. Why isn't malloc necessary here?

3. Why cast malloc's return?

4. malloc vs 'no-malloc' - help

5. REQ: Regarding malloc and free

6. REQ Dos tools for learning 'C'

7. REQ: info on 'Deep C Secrets'

8. Why am I seeing such a delay between my catch block and my finally block

9. Quick question, why does this line of code work, I have never seen that syntaxt before:

10. Cant install the VC - Samples?WHY!?

11. why cant you assign a char* to ctime()?

12. Why cant I Catch Messages from CSliderCtrl?

 

 
Powered by phpBB® Forum Software