delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/08/29/05:49:02

From: Weizhong Jiang <wj13 AT cornell DOT edu>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: More string problems!
Date: Thu, 28 Aug 1997 13:45:24 -0500
Organization: Cornell University
Lines: 62
Sender: asu1 AT cornell DOT edu (Verified)
Message-ID: <3405C744.37D0@cornell.edu>
References: <34058C10 DOT 254EBF66 AT phs DOT mat-su DOT k12 DOT ak DOT us>
Reply-To: wj13 AT cornell DOT edu
NNTP-Posting-Host: 128
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Kevin Dickerson wrote:
> 
> main()
> {
>    int l1;
>    char *chr, *buf, *text;

chr, buf and text are uninitialized pointers. since they have automatic
scope in this case, they may be pointing anywhere. what is worse, you
have not claimed the memory they are pointing to, so it writing to those
areas can do anything from just what you expected to eating your hard
drive alive.

>    for (l1=0; l1<strlen(text); l1++)
>    {
>       sprintf( chr, "%c", text[l1] );
>       strcat( buf, chr );                                          
>    }

you are writing to the locations pointed by chr and buf. 

>    printf("margarine = \"%s\"\n", buf );
> }                                       
> 
> Will compile and run without any problems,

miracle.  ;-)

> but if you change line 3 to:
> 
>    int l1, newvariable;
> 
>    Then it will report char *buf as "(null)". I'm wondering why in the
> world this will not work!

you have altered the garbage value that buf gets druing initialization.

> Memory allocation shouldn't be a problem,
> should it? I'm inclined to believe that it's a problem with strcat(),
> but I'm not positive. Argh!

it is a problem precisely because you do not allocate any. it is not a
problem with strcat. do you have access to an intro book on C? if not, i
would recommend you take a look at:

http://www.eskimo.com/~scs/cclass/notes/sx11.html

also, comp.os.msdos.djgpp is for discussion of djgpp specific topics.
for c/c++ questions, try: news:comp.lang.c and news:comp.lang.c++ and
their moderated counterparts.


> 
>    As I mentioned in my other message, I'm not a newcomer to C, but
> rather to C's blasted string functions. Thanks for your help in advance!
> 
> ---------------------------------
>                  Kevin Dickerson
>      kevind AT phs DOT mat-su DOT k12 DOT ak DOT us
>  Webmaster of Palmer High School
>      http://phs.mat-su.k12.ak.us
> ---------------------------------

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019