The second exact same statement of
str1 = (char*) malloc(sizeof(char*));
is redundant, inappropriate and useless. By doing so you allocate another memory space to which str1
is pointing to; leaving the previous allocated space because of no free()
ing abandoned but existing in memory.
char *str1;
str1 = (char*) malloc(sizeof(char*));
With that call to malloc()
you allocate memory of the size of a pointer to char
, usually 4 bytes on most modern systems, not the space needed to store a string like "Computer Engineer"
. With this definition it is only be able to store a string of 3
characters plus the automatically appended string-terminating null character (4 characters for 4 bytes).
By putting in a string longer than 3 characters by the call to scanf()
:
scanf(" %s", str1);
the program will write beyond the bounds of the allocated memory, which invokes undefined behavior (like it was high-probably happened in your case).
You need to allocate enough space to hold the provided strings - in the case of f.e. "Computer Engineer"
it needs to have at least 18 byte (Note that sizeof(char) == 1
):
char *str1 = malloc((sizeof(char) * 18);
or alternatively:
char *str1 = malloc((sizeof(*str1) * 18);
Note that you can´t put in a white space separated word by using the %s
format specifier. For achieve that, use %[
instead:
scanf("%[^\n]", str1);
Or even better use the more reliable and safer fgets()
:
fgets(str1,18,stdin);
If you want to allocate memory dependent upon the input of a user, you need to add another input request and variable before allocating:
int len;
printf("How many characters the string should have?");
scanf("%d",&len);
char *str1 = malloc((sizeof(*str1) * (len + 1)); // +1 element for null character.
printf("Enter a sentence:(Ex: Computer Engineer)");
fgets(str1,len,stdin);
Side note:
You do not need to cast the returned pointer of malloc
-> Do I cast the result of malloc?