#include<stdio.h>
int main()
{
char *ch;
int n=10;
gets(ch);
puts(ch);
printf("%d\n",n);
}
#include<stdio.h>
int main()
{
char *ch;
int n=10;
gets(ch);
printf("%d\n",n);
puts(ch);
}
In the first one , the segmentation error occurs at print(n) and in second one it occurs at puts(ch).No error occurs if print(n) is also used just after declaring n.
gets() is dereferencing an unitialized pointer, causing undefined behaviour.
Allocate memory for ch and don't use gets() as there is no way to limit the number of characters read, meaning potentially writing beyond the bounds of the destination array.
Example using fgets():
char ch[128];
if (fgets(ch, 128, stdin))
{
}
Use fgets and allocate memory for your "buffer" (via malloc) to hold the given string. At the end call free for your pointer.
#include<stdio.h>
#include<stdlib.h>
int main(){
char * ch = (char*) malloc(sizeof(char)*10);
//or by using this: char ch[10];
int n=10;
gets(ch);
puts(ch);
printf("%d\n", n);
free(ch);
}
Related
I'm in a beginner CS class learning C and we were tasked with coding a function to find string length using only string pointers. I have the following code:
#include <stdio.h>
int strlength(char* str);
int main() {
char *str;
int comp;
printf("Please enter the string: ");
scanf("%s", str);
printf("The length of the string is: %d\n", strlength(str));
return 0;
}
int strlength(char *str) {
int length = 0;
while(*str != '\0') {
length++;
str++;
}
return length;
}
I'm not really sure where I'm getting a segmentation fault. I've tried making a second pointer in the strlength function that equals str and incrementing that, but that also gives me a segmentation fault. Any insight would be appreciated!
char *str;
int comp;
printf("Please enter the string: ");
scanf("%s", str);
You should allocate memory in heap ( with malloc ) for *str before scanf. If you dont want to use malloc change it to char[number] so it can allocate memory in stack instead of heap
I'm trying to run this program by taking input from the user and I'm getting a Segmentation fault (core dumped) error. Can anyone help me to find out why this error is occurring and how can I fix this error? My code is given below:
// C program to remove the occurrences of a specific char from the given string.
#include <stdio.h>
char *squeeze(char *a[], int b){
int i,j;
for(i=j=0; *(*a+i)='\0';i++){
if(*(*a+i)!=b)
*(*a+j++)=*(*a+i);
}
*(*a+j)='\0';
return *a;
}
void main(){
char *c[1];
char d[2];
int e;
printf("Enter the string: ");
scanf("%s",*c);
printf("Enter the character to delete: ");
scanf("%c",d);
e=d[0];
printf("Resulting string is:%s.\n",squeeze(c,e));
}
You have a few problems in your code. First, as pointed out in the comments, your declaration of c as an array of char * length one is wrong. Declare it as an array of char or some max length. The will make the squeeze code simpler, with less dereferences. Next your for loop inside of squeeze is wrong, you have an assignment statement there in the middle, when you really want to check for inequality. Your second scanf needs a space in it to get rid of the white space character leftover in the input buffer. So, making these changes, your code should look something like this:
#include <stdio.h>
char *squeeze(char *a, int b){
int i,j;
for(i=j=0; *(a+i) != '\0';i++){
if(*(a+i)!=b)
*(a+j++)=*(a+i);
}
*(a+j)='\0';
return a;
}
int main() {
char c[100] = {0};
char d[2];
int e;
printf("Enter the string: ");
scanf("%99s",c);
printf("Enter the character to delete: ");
scanf(" %c",d);
e=d[0];
printf("Resulting string is: %s.\n",squeeze(c,e));
}
EDIT: Specify string length with scanf when reading in c.
// C program to remove the occurrences of a specific char from the given string.
#include<stdio.h>
char * squeeze(char a[], char b){
for(i=0; a[i]!='\0';i++){
if(a[i]==b){
a[i]=a[i+1];
while(a[i++]!='\0'){
a[i]=a[i+1];
}
}
}
return a;
}
int main(){
char c[50];
char d;
printf("Enter the string:");
scanf("%s",c);
printf("Enter the character to delete:");//add \n
scanf(" %c",&d);
printf("Resulting string is:%s\n",squeeze(c,d));
return 0;
}
What I'm trying to do in my program is to copy the content of one string to another, in reverse. This part of the program works.
However, I don't want to limit the user for input, so I want to use malloc and realloc. This is my code:
#include <stdio.h>
#include <stdlib.h>
/*copy one string to another, in reverse*/
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}
}
main(){
printf("please enter a string\n");
char c; int i=0; int end=10;
/*allocate initial memory*/
char *p=(char*)malloc(sizeof(end)); char *temp=p;
while (c!='\n')
{
/*reallocate if needed*/
if (i==(end-1)){
end*=2;
temp = realloc(p,end*sizeof(temp));
if (temp!=NULL){
/*this is for myself, to see what the error was*/
printf("error allocating\n");
exit(1);
}
else
free(p);
}
c=getchar();
p[i]=c;
i++;
}
char h [sizeof(p)];
copyStr(p,h);
}
I found out that the realloc function doesn't work and so I am asking for your help.
The program works if the input is very short (i.e 3 chars).
If it longer than 10 letters, it will not reallocate memory.
If it longer than 5, it will print reversly but will send me a message called "stack smashed".
Thank you.
In fact, there are some little tricks to change :
the *temp=realloc(... should become temp=realloc(...
The fact that temp!=NULL is the normal behavior of realloc().
do not forget to change p after the realloc operation if you use it after.
sizeof(p) is the size of a pointer, that is 4 or 8... I turned it into char h [sizeof(char)*(i+1)];
i also added the \0 character at the end of the string. This is useful if you wish to print it or use strlen() and #include string.h. Then you can printf("the result is :\n%s \n",h);
Here goes the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*copy one string to another, in reverse*/
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
//keep end-of-string character
h[length+1]='\0';
/* char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}*/
printf("the result is :\n%s \n",h);
}
main(){
printf("please enter a string\n");
char c; int i=0; int end=10;
/*allocate initial memory*/
char *p=(char*)malloc(sizeof(end)); char *temp=p;
//signaling end of string
p[0]='\0';
while (c!='\n' && c!=EOF)
{
/*reallocate if needed*/
if (i==(end-2)){
end*=2;
temp=(char*)realloc(p,end*sizeof(char));
if (temp==NULL){
/*this is for myself, to see what the error was*/
printf("error allocating\n");
exit(1);
}
else{
p=temp;
printf("ok here\n");
}
}
c=getchar();
p[i]=c;
i++;
}
//signaling end of string
p[i+1]='\0';
printf("INVERTING STRING\n");
char h [sizeof(char)*(i+1)];
copyStr(p,h);
free(p);
}
! enif krow ot smees ti
Bye,
Francis
Its not *temp its temp. Realloc returns a address of the location where the memory is allocate which you should store in pointer . not storing in the address pointed by pointer already which would make no sense
*temp=(char*)realloc(p,end*sizeof(temp));
to be
temp = realloc(p,end*sizeof(temp));
The pointer is temp, *temp refers to content.
So I'm trying to print an inputted string using putch and a little bit of pointers.
Here is my current code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void printer(char *c);
char *c;
char ch;
main(){
clrscr();
printf("Enter a string: ");
scanf("%s",&ch);
c = &ch;
printer(c);
getch();
}
void printer(char *c){
int x;
for(x=0;x<strlen(c);x++){
putch(*c);
}
}
The problem is that i can only print the first character of the string, also for some reason strlen always return 3 for strings that are 3 characters and below.
Do I have to use array for this so that I can use putch since it is limited to only 1 character output.
One of the problems is that your printer() function is not printing anything other than the first character. There are two ways of approaching this. Using pointers:
void printer(char const *c){
while ( *c != '\0' ) {
putch(*c);
c++;
}
}
And using pointer arithmetic:
void printer(char const *c) {
int x;
for ( x=0; x < strlen(c); x++ ) {
putch( *(c + x) );
}
}
The biggest problem is that you are attempting to store a string in a single character in memory. That's just asking for problems.
char ch;
scanf("%s",&ch); // NO NO NO NO NO
Instead declare your buffer (to store the string in) as an array big enough for the biggest string you expect:
char ch[512];
scanf("%s", ch);
First off, you pass a pointer to "storage for one character" to scanf. Anything that happens after that is in nsal demons territory.
Second, scanf does not allocate storage for your input, so even if you'd passed c instead of &ch, you would not be any better off.
Third, you really should be declaring your variables inside main rather than using global variables.
Something like this may be closer to what you actually want:
void output (char *c)
{
char *cp;
for (cp = c; *cp; cp++) {
putch(*cp);
}
}
int main (void)
{
char input[80];
printf("Please input a string: ");
scanf("%s\n", input);
output(input);
}
try this code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void printer(char *c);
char *c;
char buffer[1000];// use as a buffer
void main(){
clrscr();
printf("Enter a string: ");
scanf("%s",buffer);//read the input to the buffer
c=(char*)malloc(strlen(buffer)+1);//alloc memory with len of input + 1 byte to "\0"(end of string)
strcpy(c,buffer);//copy the input from the buffer to the new memory
printer(c);
getch();
free(c);//free the memeory
}
void printer(char *c)
{
int x;
for(x=0;x<strlen(c);x++){//move the index string pointer to next char in the string
putch(c[x]);//print the char to the screen
}
}
1)You cant use char to save a string u need char*!!!
2)You can get input to memory that not allocated!!!! because of that u must read the input to buffer after that alloc string by size of the input inside the buffer!
Your code print only first character because c is always pointing to first character of the array. For printing total string you need to increment character pointer as well
You need to do like this
void printer(char *c){
while(*c != '\0'){
putch(*c);
c++;
}
}
First calculate the length of the string & then use above implementation like this-
void printer(char *c){
int i, length;
length=strlen(c)
for(i=0;i<lenth;i++,c++){
putch(*c);
}
}
It should work I think.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void printer(char *c);
char *c;
char ch;//the ch should be a array
main(){
clrscr();
printf("Enter a string: ");
scanf("%s",&ch);//the ch don't need '&'
c = &ch;//the ch don't need '&'
printer(c);
getch();
}
void printer(char *c){
int x;
for(x=0;x<strlen(c);x++){
putch(*c);
}
}
Am I using scanf() in some wrong way?
char *input;
scanf("%s", input);
printf("%s\n", input);
This fails at the run-time.
Declaring a char * only creates a pointer, it does not allocate any memory for the string. You need to allocate memory for input. You can do that dynamically via malloc (and free when done) or you can declare an array of static size like char input[100].
char *input;
This is a pointer. It doesn't point to any memory.
#include <stdlib.h>
#include <stdio.h>
int main()
{
//char *input;
char input[128];
memset(input, 0 ,sizeof(input));
scanf("%s", input);
printf("%s\n", input);
return 0;
}
replace char *input; with char input[1024] = {0};
you should ensure the parameter you pass to scanf points to a buffer which could hold your input