LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
LinkBack Search this Thread
Old 06-04-2011, 08:38 AM   #1
mecrazyme1234
LQ Newbie
 
Registered: Jun 2011
Posts: 4

Rep: Reputation: Disabled
i tried using this code for deleting a user given character from a user given string


Code:
#include<stdio.h>

#include<string.h>

char* delete (char*,char);


int main()

{
       
 	char *name;
  
        char *ch=name;
        
	char c;
        
	printf("\nEnter the string and the character to be deleted");
        
	scanf("%s %c",name,&c);
        
	char* ret;
        
        ret=delete(ch,c);
        
	printf("\nthe modified string is %s",ret);
        
	return(0);

}



	

	char* delete (char* p,char t)

{  
       int l,i;
        
	l=strlen(p);
        
	printf("\n%d",l);
      
	 for(i=0;i<l;i++)
        
	{
                
		if(*p=='t')
                
		{
                 while(*p!='\0')
                        
			
			{ 
                        *p=*(++p);
                          
				p++;
                        
			}

               
		 }
       
	  p++;
        
	}
   
	  printf("%s",p);
    
	return(p);
}
******************************************************
but it showed segmentation error..pls help

Last edited by mecrazyme1234; 06-04-2011 at 11:12 AM.
 
Old 06-04-2011, 09:59 AM   #2
MTK358
LQ 5k Club
 
Registered: Sep 2009
Distribution: Arch x86_64
Posts: 6,443
Blog Entries: 3

Rep: Reputation: 707Reputation: 707Reputation: 707Reputation: 707Reputation: 707Reputation: 707Reputation: 707
Edit your post to use code tags, like this:

[code] code goes here [/code]

They preserve indentation, provide a nice scroll box, and use a monospaced font. The way it is now, you code is almost unreadable.
 
Old 06-04-2011, 10:52 AM   #3
Heraton
Member
 
Registered: Apr 2011
Location: Germany
Distribution: Mint 10, openSuSE
Posts: 42

Rep: Reputation: 1
Wink Buffers need to be initialized...

Hi mecrazyme1234!

Thanks for the code tag ;-)

The problem which causes the segfault is that you are trying to scanf into an uninitialized pointer to nowhereland.

To use scanf in the way you try, you need to provide a sufficiently large buffer for the data you read. The easiest way to do this is to change your code as follows:

Code:
// cut this line. Its just wrong: char *name;
// use this line instead:
char name[100];
This declaration makes the compiler get enough memory for 100 char. This memory can than be accessed by name.


To prevent further errors you also should change your scanf - format string as follows.
Code:
scanf("%99s %c",name,&c);
This will make the scanf function read up to 99 characters from stdin and append a terminating '\0' (100th char).

By the way, your code is broken in a few other ways too.

Edit:
You didn't understand what "the others" where trying to tell you here, did you?

Edit2:
dwhitney67 is absolutely correct about using fgets. Just listen to him ;-)

regards, Heraton

Last edited by Heraton; 06-04-2011 at 11:18 AM. Reason: corrected format string
 
Old 06-04-2011, 11:04 AM   #4
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Ubuntu
Posts: 1,160

Rep: Reputation: 232Reputation: 232Reputation: 232
Quote:
Originally Posted by mecrazyme1234 View Post
but it showed segmentation error..pls help
[rant] pls? Why not spell it correctly? [/rant]

Think about the following operation:
Code:
scanf("%s%c",name,&c);
Where do you supposed scanf() is going to store the string that is entered? Undoubtedly you want this string stored at the memory location referenced by the variable 'name'. And what memory location is 'name' referencing? (hint: random location)

If you wish for the user to enter a word and character, do you not think that the format statement above will require a white-space between the %s and %c?

Also, why use a variable called 'name'? Do you not think it would be more appropriate to use a variable called 'word' or something similar? Use of single-letter variable names should be avoided; consider declaring variables that are descriptive of the data they store.

As for using scanf() to read in a string, it is not the wisest of choices. Consider using fgets() to read the entire input from the user, and then parse the inputted string for the word and character. Using your code as an example, here's the gist of it:
Code:
#include <stdio.h>
#include <stdlib.h>

char* delete_char_from_string(const char* str, const char ch);
char* reverse_string(const char* str);

int main()
{
   char input[30];
   char word[24];
   char delete_ch;

   printf("Enter word and a character to be deleted: ");
   fgets(input, sizeof(input), stdin);    /* use fgets() to read entire input */

   /* extract word and character from input */
   if (sscanf(input, "%s %c", word, &delete_ch) != 2)
   {
      fprintf(stderr, "Failed to parse input string; exiting!\n");
      return -1;
   }

   char* new_str = delete_char_from_string(word, delete_ch);
   char* rev_str = reverse_string(word);

   if (rev_str)
   {
      printf("Reversed word: %s\n", rev_str);
      free(rev_str);
   }

   if (new_str)
   {
      printf("Word without %c: %s\n", delete_ch, new_str);
      free(new_str);
   }

   return 0;
}


/*
 *  Delete the given character from the string, without affecting the original string.
 *  A shortened string is returned, which must be freed by the caller.
 */
char* delete_char_from_string(const char* str, const char ch)
{
   /* TODO */
   return NULL;
}


/*
 *  Reverses the given string, without affecting the string.
 *  A reversed string is returned, which must be freed by the caller.
 */
char* reverse_string(const char* str)
{
   /* TODO */
   return NULL;
}

Last edited by dwhitney67; 06-04-2011 at 11:11 AM.
 
Old 06-04-2011, 11:10 AM   #5
mecrazyme1234
LQ Newbie
 
Registered: Jun 2011
Posts: 4

Original Poster
Rep: Reputation: Disabled
m sorry if i am completely wrong in my knowlegde that initializing a character pointer like:
Code:
char *name;
name="asddf";
ensures just the allocation of just the right amount of memory space for storing the string "asddf" (or whatever)..is it illegal to use the same method to take a user input as..

Code:
char *name;
scanf("%s",name);
???please help..

Last edited by mecrazyme1234; 06-05-2011 at 12:46 AM.
 
Old 06-04-2011, 11:13 AM   #6
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Ubuntu
Posts: 1,160

Rep: Reputation: 232Reputation: 232Reputation: 232
Quote:
Originally Posted by mecrazyme1234 View Post
???please help..
Help has been offered; now it is up to you to read and understand the advice that has been given.

P.S. Key library functions that you should familiarize yourself with include malloc(), strlen(), strcpy().

Last edited by dwhitney67; 06-04-2011 at 11:14 AM.
 
Old 06-04-2011, 11:29 AM   #7
MTK358
LQ 5k Club
 
Registered: Sep 2009
Distribution: Arch x86_64
Posts: 6,443
Blog Entries: 3

Rep: Reputation: 707Reputation: 707Reputation: 707Reputation: 707Reputation: 707Reputation: 707Reputation: 707
Quote:
Originally Posted by mecrazyme1234 View Post
m sorry if i am completely wrong in my knowlegde that initializing a character pointer like:
[code]
char *name;
name="asddf";
[\code]

ensures just the allocation of just the right amount of memory space for storing the string "asddf" (or whatever)..is it illegal to use the same method to take a user input as..

[code]
char *name;
scanf("%s",name);
[\code]

???please help..
You used backslashes instead or forward slashes in the code tags.

This:

Code:
name = "asddf"
doesn't load the string "asddf" into the address pointed to by "name". Instead, it pre-allocates a buffer containing "asddf", and then changes the variable "name" to point to that location.

The "name" varaible doesn't contain a valid address (or it could contain one that's valid but doesn't belong to you) until you change it to point to one. If you really wanted to copy the string "asddf" into "name" instead of changing the location to which "name" points to, do this (actually the first example does change where "name" points to, but not while writing the string data to it):

Code:
char *name;
name = malloc(sizeof(char) * 6); // tell the OS to allocate 6 chars worth of memory in the heap to this process, and set "name" to point to it
memcpy(name, "asddf", sizeof(char) * 6); // copy the string "asddf" into the block pointed to by "name".
or this:

Code:
char name[6]; // pre-allocate 6 chars in a row on the stack
memcpy(name, "asddf", sizeof(char) * 6); // copy the string "asddf" into the block pointed to by "name".

Last edited by MTK358; 06-04-2011 at 11:33 AM.
 
1 members found this post helpful.
Old 06-04-2011, 11:47 AM   #8
Heraton
Member
 
Registered: Apr 2011
Location: Germany
Distribution: Mint 10, openSuSE
Posts: 42

Rep: Reputation: 1
Quote:
Originally Posted by mecrazyme1234
is it illegal to use the same method to take a user input as..

[code]
char *name;
scanf("%s",name);
[\code]
neither law enforcement will put you in jail nor will the internet police come to confiscate your PC. But as long as you use this code, your program will cause segmentation faults.

Code:
#include <stdio.h>

int main(int argc, char * argv[])
{
	char * mypointer;
	mypointer="Hello World!";
	printf("%s\n",mypointer);
	return 0;
}
Note that it is ok to use your method of initialization to make a pointer point to a known constant string. But no string that you read at runtime will ever be considered constant in this way, as its length is not known at compile time and it will not be linked into your application. And as MTK358 explains, this "initialization" of the pointer mypointer is not getting you the memory, but is just storing the address of "Hello World!" in your pointer variable. The memory just was there, because the compiler knew at compile time that this application would need it at runtime.

Heraton
 
1 members found this post helpful.
  


Reply

Tags
printf


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
i tried using this code for deleting a user given character from a user given string mecrazyme1234 Linux - Newbie 2 06-04-2011 04:59 PM
Trying to change String using sed with a string \/home\/user\/Desktop icecoolcorey Programming 10 06-12-2008 11:32 PM
User Preferences: Use HTML code instead of vB code? (vB code is overrated) stefanlasiewski LQ Suggestions & Feedback 5 07-26-2005 01:37 AM
deleting a user joe k Linux - General 3 12-08-2004 06:31 AM
Deleting a user leecming Linux - Newbie 8 06-12-2004 02:17 PM


All times are GMT -5. The time now is 03:37 PM.

Main Menu
 
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: @linuxquestions
Open Source Consulting | Domain Registration