The "Segmentation fault (core dumped)" error occurs when using the malloc function. I learned that malloc's initialization value is filled with trash memory. Is Segmentation fault error occurring in this part?
#include <stdio.h>
#include <stdlib.h>
int chnum;
char *getstr(void)
{
char *str1 = (char *)malloc(sizeof(char) * chnum);
printf("Write a string: ");
gets(str1);
return str1;
}
int main(void)
{
printf("What is the maximum length of a string? ");
scanf("%d",chnum);
char *set = getstr();
printf("string : %s \n",set);
free(set);
return 0;
}
sizeof(char)
as it is by definition 1gets
use fgets
insteadscanf
pass the pointer to the object not the object itself.getstr
)#include <stdio.h>
#include <stdlib.h>
char *getstr(size_t chnum)
{
char *str1 = malloc(chnum);
if(str1)
{
printf("Write a string: ");
fgets(str1, chnum, stdin);
printf("\n");
}
return str1;
}
int main(void)
{
size_t chnum;
printf("What is the maximum length of a string? ");
if(scanf("%zu", &chnum) == 1)
{
printf("\n");
fgetc(stdin);
char *str = getstr(chnum);
if(str)
{
printf("string : %s \n",str);
free(str);
}
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.