Thread: strings and memory

  1. #1
    Registered User stormbringer's Avatar
    Join Date
    Jul 2002
    Posts
    90

    strings and memory

    hi

    i'm a little confused about strings and memory. if i specify a statement like:
    Code:
    char *mystring;
    
    mystring="Hello";
    what happens then? is memory allocated automaticaly or is this potentialy dangerous? would it be beter to do the folowing?
    Code:
    char *mystring;
    
    mystring=(char *)malloc((strlen("Hello")+1)*sizeof(char));
    mystring="Hello";
    especialy: what's happening if i read a string from a file e.g. with fgets and then do want to use it throughout my programm. is it sufficient to make mystring = fgets(...) or do i need to guesse the lengt and malloc it, then fill it?

    thanks

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    Code:
    char *mystring;
    
    mystring="Hello";
    This is ok as long as you realise that the string "Hello" is in static read only memory. You may not write to this string.
    Code:
    char *mystring;
    
    mystring=(char *)malloc((strlen("Hello")+1)*sizeof(char));
    mystring="Hello";
    This is a balls-up! A memory leak!
    You get dynamic memory then throw it away by repointing your pointer at a static string. To place the string "Hello" in the memory pointed to by mystring you should have used strcpy(). If you had used strcpy then this string could be modified if you wanted to unlike the first example.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User stormbringer's Avatar
    Join Date
    Jul 2002
    Posts
    90
    ok

    another question:

    if i have functions like:

    Code:
    int main()
    {
    	char *mystring = f1();
    	...;
    	f2(mystring);
    }
    
    char *f1(...)
    {
    	char *mystring;
    	fgets(mystring,100,f);
    	return mystring;
    }
    
    int f2(char *mystring)
    {	
    	do something with the string;
    }
    i'd think that this wan't work, because when exiting f1 the memory is freed and the pointer points to nirvana. right? so here i need to go the way over malloc?

    thanks

  4. #4
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>because when exiting f1 the memory is freed and the pointer points to nirvana. right?
    It won't work, but not how you think. The problem is that mystring is a pointer to garbage and you try to use fgets to read into memory you don't have. This should cause an access violation of some sort. What you need to do is allocate memory first.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char *f1(void)
    {
      char *mystring;
    
      if ((mystring = malloc(100)) == 0)
      {
        return 0;
      }
    
      fgets(mystring,100,stdin);
    
      return mystring;
    }
    
    void f2(char *mystring)
    {
      printf("%s\n", mystring);
    }
    
    int main(void)
    {
      char *mystring = f1();
    
      if (mystring != 0)
      {
        f2(mystring);
      }
    
      return 0;
    }
    *Cela*

  5. #5
    Registered User stormbringer's Avatar
    Join Date
    Jul 2002
    Posts
    90
    i see. so if i want to read a small file into memory (parts of the line, which specify options) i qould do best to write a function with a array of let's say thousand. then get the real stringlength (linelength) and malloc that much memory for each line (storing those strings in a linked list or tree or something). that would save me memory (at cost of efficency), right?

  6. #6
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    You can use standard library functions for calculating the size of a file. Use fseek() to put the filepointer at the end and then use ftell() to get the file length.

    Then you could use malloc() to allocate the necessary memory. You could allocate one block of memory for the whole file or use a linked list to store each line in a node.

    That's more efficient memory use than your proposal, because if you write a function with an array of thousand, you already have allocated that thousand bytes, but you don't know if you would need it all. On the other hand the situation could happen that you needed more than thousand bytes.

  7. #7
    Registered User stormbringer's Avatar
    Join Date
    Jul 2002
    Posts
    90
    but if the file is too large to read into memory, there's a problem. and there's no way to get the lenght of a line in an acceptable time (we could determine it by going from \n to \n with fgetc, but that will slow down the programm)
    so the only way is going over a buffer that maybe wastes memory, but when exiting the function, memory will be free and just the precisly allocated meory from the relevant lines remains.

    isn't it so?

  8. #8
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    Do you need a program that fast? Yes, when the file is too large, it won't fit in the memory and you need to implement a buffer mechanism. This does not necessarily need to be a waste of memory. You could consider the array being a queue. At the tail you add characters and at the beginning you read characters. In this way you can analyze the stream of characters and your buffer is never empty. Unless you have almost reached the end of the file or in the beginning ofcourse.

  9. #9
    Registered User stormbringer's Avatar
    Join Date
    Jul 2002
    Posts
    90
    well, i once wrote a programm scaning, converting and replacing expressions in a 8gb logfile.
    with a buffer the file runs for about half an hour or so, without two days.....

    however, what confused me was porting strings between functions. that programm did all the string stuff in one function.

    thank you all

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array of strings and memory allocation
    By maluyk in forum C Programming
    Replies: 7
    Last Post: 01-26-2009, 11:52 AM
  2. Strings and Dynamic Memory
    By grooveordie in forum C Programming
    Replies: 3
    Last Post: 10-20-2008, 02:08 PM
  3. Dynamically allocating memory for strings in a function
    By sunilkjin in forum C Programming
    Replies: 6
    Last Post: 11-22-2006, 04:43 PM
  4. Pointer's
    By xlordt in forum C Programming
    Replies: 13
    Last Post: 10-14-2003, 02:15 PM
  5. Memory handler
    By Dr. Bebop in forum C Programming
    Replies: 7
    Last Post: 09-15-2002, 04:14 PM