This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Segmentation Fault - C
#include<stdio.h>
#include<string.h>
int main()
{
char *p;
printf("enter some thing:");
gets(p);
printf("you have typed:%s\n",p);
}
Why doesn't this program work?
i can't use pointer as a string.
Output is:
enter some thing:raihan
Segmentation fault (core dumped)
I get this error every time when I use a char pointer.
How can I solve this problem?
I am using code-blocks on Linux mint13 KDE.
You have not allocated memory. You just declared a pointer, p, but didn't make it point at anything. That explains the segmentation fault. You will need to allocate memory for your buffer.
What's more, gets does not allow you to specify how big the buffer is. So you are at risk of running over the end of the buffer. So use fgets instead.
int main(void)
{
char buffer[1024];//allocates a buffer to receive the input
printf("enter some thing: ");
fgets(buffer, sizeof(buffer), stdin);
printf("you have typed: %s\n", buffer);
return 0;
}
I also corrected your declaration of main and made sure that it returns a value.
You haven't allocated any memory for p. Also, use fgets instead of gets which may overflow the input buffer.
char *p;
printf("enter some thing:");
gets(p);
Wrong. Gets() tries to fill in the array pointed to by the supplied pointer - and it segfaults, because that pointer hasn't been initialized, so it might (and does) point to some garbage/invalid memory location. Use
char p[256];
or something like this instead - you still have to worry about a buffer overflow in if the user enters a string longer than 255 characters. You can solve that one using
fgets(p, sizeof(p), stdin);
Your pointer is declared but you have not initialised it and so its value will be some arbitrary memory location that you may not have access to write to. Thus anytime you read or write to this you run the risk of segfault. Allocate some heap memory for the pointer using a call to malloc then you wont get segfaults when writing to it.
You have just defined a pointer - no memory for the characters have been allocated!
Use either an array or malloc.
A pointer is just a memory address. It says "you have some data here". But it doesn't actually reserve that data.
In your case the problem was two-fold. The pointer didn't point to valid memory and you never even set it to anything (so it pointed to somewhere random).
You can fix this in different ways. The easiest is to just use an array (it's sort of implicitly a pointer):
char something[100];
printf("enter some thing:");
gets(something);
That gives you 100 chars on the stack. You can also point to it if you want, but in this case it's a bit redundant:
char *p = something;
The other way is dynamic allocation, where you ask the operating system at runtime to give you some number of bytes. This way you have to give it back when you're finished using it.
char *something = (char*)malloc( 100 * sizeof(char) ); // Ask for 100 chars
printf("enter some thing:");
gets(something);
free(something); // Do this when you don't need that memory anymore.
PS: Remember when you have strings, you always need one extra byte than the number of characters you intend to store. That byte is for the string terminator, and the value of it is 0.
Related
#include <stdio.h>
int main ()
{
char str[40];
printf("Enter a string : \n");
gets(str);
printf("You entered: %s\n", str);
return 0;
};
in above code, if replace str to a pointer, char *str. Then NULL is out. Suppose gets defined by char *gets(char *str), it should use a pointer instead of array. All examples I saw are array not pointers. Thanks.
function gets() is depracted your libc/compiler might ignore it. try use fgets() instead.
#include <stdio.h>
int main ()
{
char str[40];
printf("Enter a string : \n");
if (fgets(str, sizeof(str), stdin) != NULL)
{
printf("You entered: %s\n", str);
}
return 0;
};
also if you want to don't use stack you need to give pointer that points allocated space. in code str also can be char *str = malloc(40); then change sizeof(str) to 40 since str is no longer stack.
Really interesting question, I have been asked this question a lot!
you should have a bit background of pointers and memory to understand what is happening.
first let's have a brief review about pointers and memory:
our computer have some memory and we can use it in programming, anything that we store (in runtime) for example an int, array of doubles, some complex struct and strings(that they are array of characters) should be somewhere in memory.
pointers contain address of somewhere in memory, some of them know about that memory (how to read/write value) some of them don't.
there is a special value for pointers (NULL) that means nowhere, if pointer is pointing to NULL, that pointer is pointing not nowhere (obviously nowhere is not a valid address in memory)
array is specific type of pointer, a const pointer that is pointing to already allocated memory in stack.
and about gets function: let's think we want to re-implement such function (namely my_gets) , how we suppose to do that? how to return a string (array of characters)?
these are options (as far as i know):
creating a local array in our function and fill it. then we should return it? no we cant! because that array is in stack of our function and after ending the function, our function data including this array will be popped automatically (handled by compiler).
although nobody forbid us from returning that array, but that would cause dangling pointer problem.
allocating some space rather than stack (heap) and fill that. this is perfectly fine and there is methods and do this! for example readline (not in ansi c, you can find it here) will do this. the drawback of this method is that you should take care of that memory and free it later, it also may be not to optimum way and you may should copy that string to your already allocated memory
the last way (and way that gets use) is getting a pointer that is already pointing to a valid memory and fill that memory. you already know that gets want a pointer as input, I add that, that pointer should point to a valid and accessible memory that gets can fill it. if pointer is pointing to NULL (or maybe uninitialized and pointing to some where random) gets will fail writing and cause undefined behavior (segmentation fault for example)
some final points:
array solution work because array name is pointer that pointing to valid memory (array in stack) so it's OK and easy to understand.
If we don't want to use array, we can point our pointer to a valid memory, we need to use malloc/calloc to allocate a block of memory. see this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size = 40 * sizeof(char);
char* p = malloc(size);
printf("Enter a string : \n");
if (fgets(p, size, stdin) != NULL) {
printf("You entered: %s\n", p);
}
free(p);
return 0;
}
gets is not secure because it doesn't care how much memory we have, it writes until and string ends and it may cause buffer overflow, better option (as people said) is fgets because it care memory size and will not exceed that. but my answer doesn't care it's fgets or gets.
While working on dynamic memory allocation in C, I am getting confused when allocating size of memory to a char pointer. While I am only giving 1 byte as limit, the char pointer successfully takes input as long as possible, given that each letter corresponds to 1 byte.
Also I have tried to find sizes of pointer before and after input. How can I understand what is happening here? The output is confusing me.
Look at this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int limit;
printf("Please enter the limit of your string - ");
gets(&limit);
char *text = (char*) malloc(limit*4);
printf("\n\nThe size of text before input is %d bytes",sizeof(text));
printf("\n\nPlease input your string - ");
scanf("%[^\n]s",text);
printf("\n\nYour string is %s",text);
printf("\n\nThe size of char pointer text after input is %d bytes",sizeof(text));
printf("\n\nThe size of text value after input is %d bytes",sizeof(*text));
printf("\n\nThe size of ++text value after input is %d bytes",sizeof(++text));
free(text);
return 0;
}
Check this output:
It works because malloc usually doesn't allocate the same number of bytes you pass to it.
It reserves memory multiple of "blocks". It usually reserve more memory to "cache" it for next malloc calls as an optimization. (it is an implementation specific)
check glibc malloc internals for example.
Using more memory than allocated by malloc is an undefined behavior. you may overwrite metadata of malloc saved on heap or corrupt other data.
Also I have tried to find sizes of pointer before and after input. How
can I understand what is happening here? The output is confusing me.
The size of pointer is fixed for all pointer types in a machine, it is usually 4/8 bytes depending on the address size. It doesn't have anything to do with data size.
Welcome to the world of Undefined Behaviour!
char *text = malloc(limit*4); (don't cast malloc in C) will make text point the the first element of an array of size limit*4.
C will not prevent you to write past the end of any array, simply the behaviour is undefined by the standard. It may work fine, or it may crash immediately, or you may experience abnormal behaviour later in the program.
Here, the underlying system call has probably allocated a full memory page (often 4k), and as you have not used another malloc you have just used a memory belonging to the process but still officially unused. But do not rely on that and never use it in production code.
And sizeof does not make sense with pointers. sizeof(text) is sizeof(char *) (same for sizeof(++text) for same reason) and is the size of a pointer (generaly 2, 4 or 8 bytes) and sizeof(*text) is sizeof(char) which by definition is 1.
C is confident that you as the programmer know how much memory you have asked, and will not try to use more. Anything can happen if you do (including expected result) but do not blame the language or the compiler if it breaks: only you will be guilty.
This question already has answers here:
segmentation fault using scanf [duplicate]
(2 answers)
Closed 7 years ago.
I'm trying to input a word in the form of a char * in C
Such as :
char *inputText;
scanf("%s",inputText);
printf("This is your string %s",inputText);
I have tried with using
scanf("%s",&inputText);
As well
Each time I either get a compile error or Segmentation fault when I run it
"format '%s' expects type 'char *' but argument 2 has type 'char **'
I'm not sure if I'm missing something really simple but It's quite confusing.
My code depends on using char *
If theres a way to convert an easier input method into char * then can you show me that method?
You haven't initialized inputText so it's pointing to some random memory which you probably don't even own. Asking scanf write to that memory location results in undefined behavior.
You need to allocate memory for the pointer to point to:
char *inputText = malloc(amount_of_bytes_to_allocate);
Now inputText points to the allocated memory, and scanf can happily write to that memory location without a segfault. Remember that you must free(inputText) when you're done using the allocated memory.
But preferably, you wouldn't use dynamic memory (malloc) in this case since you can do just fine with automatic memory: just declare inputText as an array instead of a pointer:
char inputText[size_of_array];
Remember that your size_of_array (or amount_of_bytes_to_allocate) must be large enough to hold the entire string that scanf is going to write into the array, including the terminating null character. Otherwise you'll have undefined behavior again.
First, as a general precaution, it's a good idea to initialize new pointers to NULL so as to ensure they aren't pointing to memory that your program isn't allowed to access.
I would use getline() as an alternative to scanf() especially if the size of your input can vary. It allocates a properly-sized buffer for you, so you don't need to worry about entering too many characters.
char *inputText = NULL;
int inputSize;
if (getline(&inputText, &inputSize, stdin) >= 0)
printf("This is your string: %s\n", inputText);
else
printf("Error\n");
You still need to free the memory allocated to inputText yourself, so don't forget to do that and set it to NULL once you're done with it.
This question already has answers here:
why scanf scans a null value
(2 answers)
Closed 8 years ago.
I'm sure there just a silly mistake here, however, I can't figure it out.
This is part of my code:
char *moving;
scanf("%s", moving);
When I compile it with gcc, it says the following:
newmatrix.c:38:7: warning: ‘moving’ is used uninitialized in this function [-Wuninitialized]
Line 38 is the scanf
How do I fix this?
Thanks
You can allocate memory before you call scanf(). For example:
char moving[256];
if (scanf("%255s", moving) != 1)
…oops — presumably EOF…
You could use malloc() instead of a simple array, but then you have to remember to free the allocated memory. OTOH, if you want to return the data from the function where it is read, it may well be more convenient to use malloc(), but consider passing a pointer to the space (and its size?) to the function.
Or you can have scanf() do the memory allocation for you (check the manual page for scanf() carefully — read it weekly until you've memorized (enough of) it):
char *moving;
if (scanf("%255ms", &moving) != 1)
…oops — probably EOF, but perhaps OOM (out of memory)…
…use moving…
free(moving);
Yes, this is one of the lesser-known options in POSIX-standard scanf(); it is not a part of Standard C.
Allocate memory for moving before using it. Use malloc().
moving is pointer of char type. Before storing the string in moving, you need to allocate memory for it.
char *moving;
moving = malloc(100);
scanf("%s", moving);
OR
Simply change char *moving to char moving[256].
Also instead of scanf() use fgets().
allocate memory to the pointer before using it
char *moving;
moving = malloc(100*sizeof(char));
scanf("%s", moving);
I don't know why this code shows Segmentation Fault.Below is the code
int main()
{
char *str;
printf("\nEnter a string - \n");
scanf("%s",str);
printf("%s\n",str);
}
What can be the reasons for the segmentation fault?
Also I would like to know why using gets()function is dangerous in Linux?
Firstly, you may need to know that you could have used char str[40] = {0}; (compile time memory allocation).
Since you have asked a question which queries about dynamic memory allocation, you should allocate memory to a pointer before trying to store anything. Beacuse the pointer may be pointing to any random locations (wild pointer) and hence you may try to access memory which is not meant for accessing, this results in a segfault.
int main()
{
char *str;
str = malloc(sizeof(char) * 40); // allocate memory where str will be pointing,here i allocate 40 bytes
printf("\nEnter a string - \n");
scanf("%39s",str);
printf("%s\n",str);
free(str); //important to release the memory!
}
To answer your second question, gets() is dangerous on any platform because it may cause buffer overflow.
Consider a scenario where you try to fill a buffer beyond it’s capacity :
char *buff = malloc(sizeof(char)*10);
strcpy(buff, "This String Will Definitely Overflow the Buffer Because It Is Tooo Large");
As you can see that the strcpy() function will write the complete string in the ‘buff’ but as the size of ‘buff’ is less than the size of string so the data will get written past the right boundary of array ‘buff’. Now, depending on the compiler you are using, chances are high that this will get unnoticed during compilation and would not crash during execution. The simple reason being that memory belongs to program so any buffer overflow in this memory could get unnoticed.
So in these kind of scenarios, buffer over flow quietly corrupts the neighbouring memory and if the corrupted memory is being used by the program then it can cause unexpected results.
Workaround for safety :
char *buf=NULL;
size_t siz= 30;
ssize_t len = getline(&buf,&siz,stdin);
How is this a workaround?? Well, you should read about the getline() more.