In this program
# include <stdlib.h> # include <stdio.h> int main() { char *a = (char*) malloc(6*sizeof(char)); char *str="Hello"; *a=*str; printf ("%s\n", *a); free (a); return 0; }
you first dynamically allocate memory for a character array
char *a = (char*) malloc(6*sizeof(char));
Consequently, pointer a now contains the address of the first byte of this chunk.
Then you assign the first character of the string literal "Hello" first byte of memory pointed to by a
*a=*str;
Now you have allocated memory
'H' и некоторый "мусор"
Since the remaining bytes of the allocated memory were not initialized.
In the printf function, you use the %s format specifier, which assumes that the corresponding argument is a string, that is, a character array that has a terminating zero '\0' .
However, your string does not contain a trailing zero. Therefore, this function tries to output all characters to the console even beyond the allocated memory area until it encounters the terminator '\0' .
As a result, you get a memory segmentation error.
Moreover, you specified this first character of the string instead of the address as an argument.
printf ("%s\n", *a); ^^^
Must be at least
printf ("%s\n", a); ^^
As for this code snippet
char *array = (char*)malloc(6*sizeof(char)); array= "Hello";
That, firstly, there is a "leak" of memory. You first allocated the memory dynamically and assigned its address to the array pointer. And then this pointer was assigned the address of a string literal (its first character). As a result, the address of the dynamically allocated memory was lost.
For this code fragment, the most likely cause of the error is that you tried to free up memory using the free function by writing
free( array );
In this case, the function will try to remove the static memory occupied by the string literal, since at the moment the array points to a string literal. However, you cannot remove static memory using the free function, since this memory was not dynamically allocated. it was reserved by the compiler at compile time when I encountered a string literal in your program. This is the memory that is released by the system after the program is completed.
It would be correct to write
#include <string.h> //... char *array = (char*)malloc(6*sizeof(char)); strcpy( array, "Hello" ); //... free( array );
And in the first program instead
*a=*str;
you should write
strcpy( a, str );
having previously included the header <string.h>