6 Replies - 2236 Views - Last Post: 19 February 2011 - 08:25 AM Rate Topic: -----

#1 realsaid  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-February 11

How to resolve Segmentation fault/Error in C program manipulating stri

Posted 18 February 2011 - 05:18 AM

I have been trying to identify where my program generates segmentation fault/error all to no avail.
I need help in pin-pointing which of the strings operations or char pointers is causing the segmentation fault during runtime and how to fix it. The program compiles successfully but gives segmentation error during run-time.

 #include<curses.h>
 #include <strings.h>
 #include<unistd.h> 
 #include<stdlib.h>
 //Implements a Scrolling headband that takes a string  //argument and continously scrolls                
   int main(int argc, char* argv[]){
/*A Substring function to return substring of a string*/
      char *substr(const char *src, int start, int len);
/*Appends a character to the Given string*/
      void append(char* s, char c);
 /***Check if the argument is invalid***/
     if(argc!=2)
{
 puts("Invalid number of arguments: Usage:headband <String>");
			}
     	/**Get headtext from the string argument argv[1]**/
		char *headtext = argv[1];

/*temporary variable to store strings as execution progresses*/
		char temp[100];
/*Counter for streaming and scolling headband text*/
		int count = 0;
/*Placeholder for temporary headband text*/
		char hold[100];
		int i;
/*maximum x and y co-ordinates of the Screen*/
		int max_x,max_y;
/*Initialize screen for ncurses*/
		initscr();
/*Don't show cursor*/
		curs_set(0);
/*Get terminal console dimensions*/
		getmaxyx(stdscr, max_y, max_x);
/*Get console width set to default console screen width=80*/
		int consolewidth = max_x;
/*Clear the screen*/
		clear();
/*Set the first value as end of String for the momment*/
		temp[0] = '\0';
/*Run this loop continuously to keep scrolling*/
		for (;;)/>
		{
			for(i=0; i < strlen(headtext); i++)
			{
				count++;
/*Append headband text character by character to string hold*/
			append(temp, headtext[i]);
			move(0,consolewidth - count);
			if (consolewidth - count > 0)
				{
					 mvaddstr(0,console_width-count,temp);
				refresh();
				}
		else if (consolewidth - count == 0)
				{
					strcpy(hold, temp);
					char q;
					int com = i;
					for(;;)/>
	{/*Scroll text by triming one character at a time*/ 
        /*from the left, then adding that character to the*/
		/*right side of the text*/
		com = com + 1;
	if (com < strlen(headtext)){
	q = headtext[com];
	}else{
	com = 0;
        q = headtext[com];
	//q = hold[0];
	}
       strcpy(hold, substr(hold, 1, strlen(hold) - 1));
       append(hold, q);
	move(0,0);
	clear();				  mvaddstr(0,0,hold);
	refresh();
	usleep(50);
	}
		}
		usleep(50);
		}
		}
		return 0;
	}

/*A Substring function to return substring of a string*/
	char * 
	substr(const char *src, int start, int len) 
	{   
		char *dest = malloc(len+1);   
		if (dest) 
		{
			memcpy(dest, src+start, len);     
			dest[len] = '\0';   
		}   
		return dest;
	}

	/*Appends a character to the Given string*/
	void append(char s[], char c)
	{
			int len = strlen(s);
			s[len] = c;
			s[len+1] = '\0';
	}




Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: How to resolve Segmentation fault/Error in C program manipulating stri

#2 chinchang  Icon User is offline

  • Indie Game Developer
  • member icon

Reputation: 192
  • View blog
  • Posts: 725
  • Joined: 22-December 08

Re: How to resolve Segmentation fault/Error in C program manipulating stri

Posted 18 February 2011 - 05:42 AM

You can find which part of your program gives a segmentation fault by isolating different statements one at a time.
Do so by commenting rest of the code that operates on the strings.

When you get the error, try resolving it. If still not able to debug, let us know. Debugging your code is very important to be a good programmer. Atleast find WHAT gives error, if not WHY.

This post has been edited by chinchang: 18 February 2011 - 05:44 AM

Was This Post Helpful? 1
  • +
  • -

#3 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6066
  • View blog
  • Posts: 23,526
  • Joined: 23-August 08

Re: How to resolve Segmentation fault/Error in C program manipulating stri

Posted 18 February 2011 - 05:52 AM

Or you do the right thing and compile in debug mode and run it in the debugger to find out

1. exactly where it's seg faulting
2. what the contents of the variables are at the time of the seg fault.

Quicker and easier than using print statements.
Was This Post Helpful? 1
  • +
  • -

#4 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1689
  • View blog
  • Posts: 3,209
  • Joined: 30-May 10

Re: How to resolve Segmentation fault/Error in C program manipulating stri

Posted 18 February 2011 - 06:41 AM

What else is different between your posted code and your attached code?
			if (consolewidth - count > 0)
			{
				mvaddstr(0,console_width-count,temp);
				refresh();
			}
...
$ gcc -g bar.c
bar.c: In function ‘main’:
bar.c:69: error: ‘console_width’ undeclared (first use in this function)
bar.c:69: error: (Each undeclared identifier is reported only once
bar.c:69: error: for each function it appears in.)



It doesn't crash for me (your attachment, with fixed include files), but it does leak memory like a sieve.
==4466== HEAP SUMMARY:
==4466==     in use at exit: 259,900 bytes in 1,204 blocks
==4466==   total heap usage: 1,206 allocs, 2 frees, 259,950 bytes allocated
==4466== 
==4466== LEAK SUMMARY:
==4466==    definitely lost: 169,120 bytes in 1,057 blocks
==4466==    indirectly lost: 0 bytes in 0 blocks
==4466==      possibly lost: 0 bytes in 0 blocks
==4466==    still reachable: 90,780 bytes in 147 blocks
==4466==         suppressed: 0 bytes in 0 blocks


Your substr() function allocates memory, but it is never released.
Was This Post Helpful? 2
  • +
  • -

#5 realsaid  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-February 11

Re: How to resolve Segmentation fault/Error in C program manipulating stri

Posted 19 February 2011 - 06:35 AM

Thanks Salem, Chinchang and JackofAlltrades,
I checked the program once again on a default Unix terminal Console (i.e. Not maximized, opened within Gnome)and it worked perfectly without the segmentation error.
However, on maximizing the console the program was printing from the middle of the screen and scrolling to the left. After a few seconds it generated the segmentation error.
I found out that the stdscr window I was printing to using ncurses library had it's own maximum screen width which is not that of the console, so it won't print outside it's window.

Is there a way I can get the screen dimensions of a Unix console, print strings/characters to a particular location on the screen or move the cursor to a particular screen position without using the ncurses library in c.

I have searched to figure this out but to no avail.

For my substr()function, how do I release the allocated memory, when I used free(dest) the program generated a glibc detected *** headband: free(): invalid next size (fast): 0x09a380e0 ***
Segmentation fault (core dumped)".
I have searched to figure this out but to no avail.
Thanks.


View PostSalem_c, on 18 February 2011 - 06:41 AM, said:

What else is different between your posted code and your attached code?
			if (consolewidth - count > 0)
			{
				mvaddstr(0,console_width-count,temp);
				refresh();
			}
...
$ gcc -g bar.c
bar.c: In function ‘main’:
bar.c:69: error: ‘console_width’ undeclared (first use in this function)
bar.c:69: error: (Each undeclared identifier is reported only once
bar.c:69: error: for each function it appears in.)



It doesn't crash for me (your attachment, with fixed include files), but it does leak memory like a sieve.
==4466== HEAP SUMMARY:
==4466==     in use at exit: 259,900 bytes in 1,204 blocks
==4466==   total heap usage: 1,206 allocs, 2 frees, 259,950 bytes allocated
==4466== 
==4466== LEAK SUMMARY:
==4466==    definitely lost: 169,120 bytes in 1,057 blocks
==4466==    indirectly lost: 0 bytes in 0 blocks
==4466==      possibly lost: 0 bytes in 0 blocks
==4466==    still reachable: 90,780 bytes in 147 blocks
==4466==         suppressed: 0 bytes in 0 blocks


Your substr() function allocates memory, but it is never released.

This post has been edited by realsaid: 19 February 2011 - 06:44 AM

Was This Post Helpful? 0
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6066
  • View blog
  • Posts: 23,526
  • Joined: 23-August 08

Re: How to resolve Segmentation fault/Error in C program manipulating stri

Posted 19 February 2011 - 06:54 AM

Quote

For my substr()function, how do I release the allocated memory

As you are currently using it, you are creating a temporary variable which you cannot release. You need to create a variable to hold the result of the substr function, upon which you can call free after using it in the strcpy.

Quote

Is there a way I can get the screen dimensions of a Unix console

The environment variables COLUMNS and LINES would be helpful, as would catching the SIGWINCH signal.

Quote

print strings/characters to a particular location on the screen or move the cursor to a particular screen position

Only ever used curses for this.
Was This Post Helpful? 0
  • +
  • -

#7 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1689
  • View blog
  • Posts: 3,209
  • Joined: 30-May 10

Re: How to resolve Segmentation fault/Error in C program manipulating stri

Posted 19 February 2011 - 08:25 AM

Quote

For my substr()function, how do I release the allocated memory, when I used free(dest) the program generated a glibc detected *** headband: free(): invalid next size (fast): 0x09a380e0 ***
Segmentation fault (core dumped)".

Invalid heap pointers typically mean you overwrote memory.

But you should be doing something like this
char *temp = substr(hold, 1, strlen(hold) - 1);
strcpy(hold, temp);
free(temp);
append(hold, q);



You would have to post your latest code for more detailed answers.

For debugging, start with
gcc -g prog.c

Then type
gdb ./a.out

At the prompt, type 'run'
When it crashes, type 'bt' to see where you are in the code, which functions are stacked at the moment.

See the gdb manual for more detail, for example on printing the values of variables.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1