I'm studying C language.
The following malloc function program was written in the reference book.
str=(char*)
I don't know what's going on.
I would appreciate it if you could explain.
#include<stdio.h>
# include <stdlib.h>
int main (void)
{
char*str;
int num, i;
printf("How many letters of A do you want to prepare?\n");
scanf("%d", & num);
str=(char*)malloc(sizeof(char)*(num+1));
if(!str){
printf(" Failed to free memory.\n");
return1;
}
for(i=0;i<num;i++){
*(str+1) = 'A';
}
*(str+num)='\n;
printf("%s is ready.\n", str);
free(str);
return 0;
}
Before we talk about malloc()
, what is a string
char
array or equivalent continuous region'\0'
Ending with charactersThat's it.
char hello[] = "Hello!";
If so, it is truly an array.The compiler attaches '\0'
characters that are not written on the source code to the !
and thus meets the previous "string" criteria.Incidentally, this array variable hello
is an array of a total of seven characters.
Now what malloc(n)
does is
n
byte contiguous memory space somewherechar
the size that can be storedmalloc(n)
(=continuous memory space) can contain at least n
charactersn
characters) n+1
characters must be assumed to not be storedSo far, it matches the first and last conditions of the previous string.Additionally, you can treat the result of malloc()
as a string if you satisfy another condition of '\0'
.
num
Contains 'A'
characters'\0'
after itmalloc()
must pass num+1
It would be a commentary if I could understand that
I added a comment.
I hope it will be helpful.
#include<stdio.h>
# include <stdlib.h>
int
main(void){
// US>Declaring variable
char*str;
int num, i;
// Accepting user input
// Enter the number of A's to be prepared in the variable num.
printf("How many letters of A do you want to prepare?\n");
scanf("%d", & num);
// Normally, we should validate the input values around here, but it doesn't seem to be doing anything.
// Replace the address of the memory reserved by malloc with the pointer variable str of type char*
//
// For the malloc argument, pass the number of bytes of memory to reserve.
// You can see the number of bytes of char in size of (char).
// Multiply the number of bytes by (num+1) minutes
// The number of bytes in char is 1 byte, so if num is 10, 1*(10+1), that is, 11 bytes of memory will be reserved.
// (num+1) is +1 because it is a null character that terminates the string.
//
// malloc returns void* as the return value.
// This code seems to explicitly cast the return value of malloc as (char*)
// C has an implicit type conversion, so removing this cast has no effect on the behavior.
str=(char*)malloc(sizeof(char)*(num+1));
// Checking return value for malloc
// malloc returns NULL when memory fails.
// The definition of NULL depends on the processing system, but it is often expressed as (void*) 0.
//
// if(!str){}
//
// This if statement is true when str is NULL.
// So if you fail to get memory, it's true.
if(!str){
// Error message due to memory failure
// Usually, it is output to stderr, but in this code, it seems to be output to stdout.
printf(" Failed to free memory.\n");
// Returns 1 because the program failed to process.
// The main function returns 0 on success and 0 on failure.
// This value can be found in echo$? on bash etc.
return1;
}
// It appears that you set the value for str in the for statement.
// But the content of this for statement doesn't make much sense.
// I'm turning the loop around num, but what I'm doing is meaningless.
// *(str+1) is the syntax sugar of str[1].
// In other words, *(str+1) is the same as str[1].
// The subscript is 1, so I keep accessing str[1] even if I loop it around.
// The letter 'A' is substituted for str[1] num times.
//
// This is probably a str[i] mistake.
// str[i] = 'A'
// If so, the letter 'A' will be substituted from str 0 to num-1.
for(i=0;i<num;i++){
*(str+1) = 'A';
}
// New line is substituted for the num character of str
// *(str+num) is the same as str[num]
//
// Probably, but this is...
// *(str+num) = '\0'
// It's probably a mistake that
*(str+num)='\n';
// I'm outputting an initialized str, but this output doesn't work.
// malloc reserves memory without initializing it
// In other words, the memory we've secured has a false value.
// The C string must be null-terminated to output correctly.
// Printf does not work properly because none of the previous processes have replaced null characters.
//
// for proper functioning
// str[num] = '\0'
// You must null-terminate str on the
printf("%s is ready.\n", str);
// Freeing up the memory we've secured
free(str);
return 0;
}
Try compiling with this.
#include<stdio.h>
# include <stdlib.h>
int main (void)
{
char*str;
int num, i;
printf("How many letters of A do you want to prepare?\n");
scanf("%d", & num);
str=(char*)malloc(sizeof(char)*(num+1));
printf("You have reserved %d characters + 1 minute of data space for address %p.\n", str, num);
if(!str){
printf("Failed to free up data space (memory).\n");
return1;
}
for(i=0;i<num;i++){
printf("Write A to address %p\n", str+i);
*(str+i)='A';
}
printf("Write null('\\0') to address %p\n", str+num);
*(str+num)='\0';
printf("%s\n", str);
printf(" is ready.\n");
free(str);
return 0;
}
© 2024 OneMinuteCode. All rights reserved.