TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Herman Schonfeld
from: Darin McBride
date: 1998-08-11 22:33:12
subject: global pointers

HS> CRAP.C
 HS> ----------------------------------------------
 HS> #include 
 HS> #include 
 HS> #include 


 HS> char *text;


 HS> int main()
 HS> {
 HS>    FILE *fp = fopen("CRAP.C", "r+");

 HS>    fgets(text, 100, fp);

 HS>    return 0;
 HS> }

 HS> // this fails to run. If i declare `text' inside main() it does work.
 HS> // why does this happen? Is there something about 
 HS> globally declared pointers
 HS> // that make them function differently from internally declared pointers?

Yes, there's a significant difference between them.  In fact, if you had:

int main()
{
  static char* text;

  // rest of code
}

This, too, would fail to run.  Your 'working' version only works on DOS,
however, and even then, should fail in protected-mode (32-bit, usually)
DOS.  That's because a variable allocated on the stack is uninitialized
(contains garbage), and the standard says that variables not otherwise
explicitly initialized that are global in duration (i.e., last throughout
the program, such as global variables and static variables) are initialized
to zero, or the equivalent thereof (i.e., NULL for pointers).

You need to allocate the 100 characters for fgets:

char* text = malloc(100);

This will work both globally and locally, as well as a static pointer. 
This will even work in pmode.

Hope this helps,


---
* Origin: Tanktalus' Tower BBS (1:250/102)
SEEN-BY: 396/1 622/419 632/371 633/260 267 270 371 634/397 635/506 728 810
SEEN-BY: 639/252 670/213 218
@PATH: 250/102 201 99 396/1 633/260 635/506 728 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.