when i'm tryin' to use malloc with string pointers to scan, it's givin' a segmentation fault
main(){
char *a;
a = (char)malloc(50);
printf("enter a string\t");
scanf("%s", a);
printf("%s\n", a);
}
when i'm tryin' to use malloc with string pointers to scan, it's givin' a segmentation fault
main(){
char *a;
a = (char)malloc(50);
printf("enter a string\t");
scanf("%s", a);
printf("%s\n", a);
}
a = (char)malloc(50);
Here, you meant to cast its type to char *
instead of char
.
Note that it's better not to cast the return type of malloc
. See Do I cast the result of malloc?
Your main problem, apart from your using scanf
is that you're casting a pointer (which is size 4 or 8 on 32 or 64 bit systems respectively) to a char
, which is guaranteed to be size 1 as per standard.
Do not ignore compiler warnings. You should've seen something along the lines of:
warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
a = (char) malloc(10);
warning: assignment makes pointer from integer without a cast [enabled by default]
a = (char) malloc(50);
Casting a pointer type to char
, only to assign it to a pointer variable makes no sense. If you want to make it absolutely clear that you are allocating enough memory to accomodate N chars, then you could write:
a = malloc(50 * sizeof(char));
//or better still
a = malloc(50 *sizeof *a);//50 times the size of whatever type a is pointing to...
But a char is always size 1, like I said before. Anyway: I set about fixing the code you posted:
The following copy-pasted code works just fine, provided you don't enter more than 49 chars:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char *a = malloc(50);
if (a == NULL) return EXIT_FAILURE;//<-- no memory available
printf("enter a string\t");
scanf("%s", a);
printf("%s\n", a);
free(a);//<== be tidy, free your memory, though here, it's a bit redundant
return 0;
}
But really, look into alternatives to scanf
, and never cast the pointer returned by malloc
in C. C++ is a different matter.
Also, check for NULL pointers, to be safe.
Lastly: Don't ignore compiler warnings.
you can provide stdin input at the bottom right hand side of the page, it'll print the string you provided