Given program is working for string that is fixed in code for example
char str[100] = "With fixed string this code works"
// Output of the program is "fixed string this code works"
But as soon as I take the str
input using
scanf("%s", &str);
it seems error is found with memory allocation because after input is given code returns error value.
The full code is as following
int main (void) {
char str[100];
char *p = (char *)malloc(sizeof(char) * str[100]);
printf("Enter something: ");
scanf("%s", &str);
*p = str;
p = strchr(str, ' ');
puts(p + 1);
// Check for the first space in given input string if found then
while (*p++)
if (*p == ' ' && *++p)
printf("%s", *p);
printf ("\n\n");
return 0;
}
Not sure if for dynamic memory allocation while using scanf
function to input string any other allocation process is required
You have four problems:
First: with scanf
, it should be like that:
scanf("%s",str);
because str
is an address. Also make sure that scanf
will scan for a string from stdin
until it finds space or new line and that what you don't want. So you'd better use fgets(str, 100, stdin);
.
Second: with malloc
, it should be like that:
malloc(sizeof(char)*100)
because str[100]
has not a specific value.
Third: You shouldn't change the address of memory allocated using malloc
malloc
function allocates memory in heap and return the address of memory allocated, so you shouldn't do this p = strchr(str, ' ');
since strchr
will return the address of the first occurrence of the space (the address returned by malloc
will be lost) .
Fourth: freeing the memory allocated using malloc
You should free the memory allocated using malloc
using free
function which take the address of the memory allocated.
Your code should be like that:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
char str[100];
char *p = malloc(sizeof(char)*100); //Do NOT cast the return of malloc
printf("Enter something: ");
fgets(str, 100, stdin); //Use fgets to include the spaces between words
strcpy(p, str);//use stcpy to Not change the address of memory allocated
//p = strchr(str, ' '); -->This step will change the address
//of memory allocated using malloc
//puts (p + 1);
/*Instead you can do this*/
char *c = strchr(str, ' ');
puts(c+1);
// Check for the first space in given input string if found then
char *mem =p;
while (*p++)
if (*p == ' ' && *++p)
printf ("%s", p);
printf ("\n\n");
free(mem);
return 0;
}