Thread: Segmentation fault when appending to strings (char *)

  1. #1
    Registered User
    Join Date
    May 2010
    Location
    San Jose, California, United States
    Posts
    22

    Segmentation fault when appending to strings (char *)

    So I'm trying to implement this simple program which essentially parses a simple (untabbed, simple tags) XML file and returns it in a tabbed format, but I've been stuck on trying to append to a string...

    Code:
    #include <stdio.h>
    #include <string.h>
    // Echo stdin to stdout with trailing \n newlines
    int main(int argc, char**argv) {
      char c;
    	char *str;
    	int swtch = 0;
      c = getchar();
    	int depth = 0;
      while (c != EOF) {
    		while (c != '\n')
    		{	str = "";
    			if (c == '<')
    				swtch = 0;
    			else if (c == '>')
    			{	if (swtch == 0)
    					depth++;
    			}	else if (c == '/')
    				depth-=2;
    			strcpy(str,&c);
    		}
    		int i = 0;
    		while (i < depth)
    		{	printf("   "); i++;	}
    		printf("%s",str);
    		putchar(c);
    		c = getchar();
    		}
      return 1;
    }
    I've tried strcpy(str,&c), strncpy(str,&c,sizeof(str)), and strlcpy(str,&c,sizeof(str)), but I get a segmentation fault every time..
    How do I add one string variable to another?

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    A string is a char array whose last element is a zero byte.
    1) You haven't allocated memory for str. You should probably define it as str[100], or use malloc() to obtain memory of some appropriate number of bytes.
    2) You can't concatenate a single char to a string using strcpy, strcat, etc. unless both strings are NULL terminated.
    To assign a single character, you need to just str[n] = c, and keep track of the n index, starting at 0 and incrementing each time. Then put in a '\0' as the last element before attempting to print this string using printf.

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    San Jose, California, United States
    Posts
    22
    Thanks for the quick reply.
    So how would I go about using malloc(), and how much space should I allocate?

    To give you an idea, this is what I am looking to parse (one line at a time):
    Code:
    <level1>
    <level2>
    </level2>
    <level2>
    <deeper>
    <evendeeper>
    </evendeeper>
    </deeper>
    </level2>
    <notasdeep>
    </notasdeep>
    </level1>

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    In addition to nonoob's comments you also can't do this:
    Code:
    str = "";
    C does not assign strings with the = sign. To reset a string use numerical assignment: str[0] = 0;

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    char c;
    char *str;
    int swtch = 0;
    c = getchar();
    int depth = 0;
    while (c != EOF) {
    getchar returns an int, not a char, this is especially important as you are comparing against EOF.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    May 2010
    Location
    San Jose, California, United States
    Posts
    22
    getchar returns an int, not a char, this is especially important as you are comparing against EOF.
    Why does it return an int?
    Is there a function that can read a line from standard input (ie: keyboard input) and save it as a string? That's really what I need to make this program function..

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by LanguidLegend View Post
    Why does it return an int?
    Is there a function that can read a line from standard input (ie: keyboard input) and save it as a string? That's really what I need to make this program function..
    You could try scanf() or fscanf() whichever is best suited to your application.

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by LanguidLegend View Post
    Why does it return an int?
    Is there a function that can read a line from standard input (ie: keyboard input) and save it as a string? That's really what I need to make this program function..
    Because it needs to be able to return all possible char values plus special things like EOF, thus just a char isn't enough. Look into fgets for reading a whole line from stdin.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by CommonTater View Post
    In addition to nonoob's comments you also can't do this:
    Code:
    str = "";
    C does not assign strings with the = sign. To reset a string use numerical assignment: str[0] = 0;
    Of course you can! You are assigning the string literal "" to the pointer str. You can assign string literals to character pointers any time you want. It's not what he wants to do here, but you can do it.


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    May 2010
    Location
    San Jose, California, United States
    Posts
    22

    Smile

    Thanks everybody, I think I understand the issue much better now.

    SO this boils down to the ultimate goal of my program, to parse bracketed tags (opening & closing tags like in XML), and return them in their correct format (tabbed correctly).
    This is what I have thus far:
    Code:
    int main(int argc, char**argv) {
      char c;
      int swtch = 0;
      c = getchar();
      int depth = 0;
      while (c != EOF) {
    		if (swtch == 1)
    		{	int i = 0;
    			while (i < depth)
    			{	printf("   "); i++;	}
    		}
    		if (c == '\n')
    			swtch = 1;
    		if (c == '<')
    			swtch = 0;
    		if (c == '>' && swtch == 0)
    			depth++;
    		if (c == '/')
    			depth-=2;
    		putchar(c);
    		c = getchar();
    	}
      return 1;
    The issue I'm having is the cycle of reading and writing: by the time my program runs across the '/' character, signalling a closing tag, it has already printed the (incorrect) tab to the screen.
    How can I determine if a tag is closing before the line has been written to the screen?

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by LanguidLegend View Post
    How can I determine if a tag is closing before the line has been written to the screen?
    Read before you write.


    Quzah.
    Hope is the first step on the road to disappointment.

  12. #12
    Registered User
    Join Date
    May 2010
    Location
    San Jose, California, United States
    Posts
    22
    Quote Originally Posted by quzah View Post
    Read before you write.


    Quzah.
    Yes I thought about that, but once I process a character via getchar(), I can't revisit it.
    Which is why I was trying to make a char array (ie: a string) to store each line before exiting the while loop (so I could insert the correct tab followed the by the line).
    But then there seemed to be so many issues (the segmentation error when trying to append to the tab string, the fact that getchar() returns ints not chars)..

    Oh, and FYI, I am implementing this by writing the untabbed tags in a text file (testdata) and executing as follows:
    ~$ gcc HW1B.c -o hw1b
    ~$ ./hw1b < testdata
    Last edited by LanguidLegend; 02-24-2011 at 04:10 PM.

  13. #13
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Quote Originally Posted by LanguidLegend View Post
    Why does it return an int?
    Is there a function that can read a line from standard input (ie: keyboard input) and save it as a string? That's really what I need to make this program function..
    Look up fgets().

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by LanguidLegend View Post
    Yes I thought about that, but once I process a character via getchar(), I can't revisit it.
    Which is why I was trying to make a char array (ie: a string) to store each line before exiting the while loop (so I could insert the correct tab followed the by the line).
    But then there seemed to be so many issues (the segmentation error when trying to append to the tab string, the fact that getchar() returns ints not chars)..
    The problem then is the way you are processing things. You should be building an output buffer, and once you are done with all of your reading, then write the output. Not writing while you're reading.


    Quzah.
    Hope is the first step on the road to disappointment.

  15. #15
    Registered User
    Join Date
    May 2010
    Location
    San Jose, California, United States
    Posts
    22
    Quote Originally Posted by quzah View Post
    The problem then is the way you are processing things. You should be building an output buffer, and once you are done with all of your reading, then write the output. Not writing while you're reading.


    Quzah.
    Can you give me an example of how to build an output buffer then write it to the screen? Sorry for my inexperience..
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need help :(
    By ramenen in forum C++ Programming
    Replies: 1
    Last Post: 02-17-2010, 04:31 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  4. Searching and matching strings: segmentation fault
    By Smola in forum C Programming
    Replies: 18
    Last Post: 07-11-2005, 12:25 AM
  5. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM

Tags for this Thread