简体   繁体   中英

“Segmentation fault (core dumped)” error when using malloc function

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;
}
  1. Casting result of the malloc is considered as a bad practice.
  2. Do no use global variables to pass the data between the functions. Use function parameters for it
  3. You do not have to sizeof(char) as it is by definition 1
  4. Always check the result of malloc
  5. Do not use gets use fgets instead
  6. Always check the result of scanf.
  7. In scanf pass the pointer to the object not the object itself.
  8. Check result of the function which can fail ( 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM