-2

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;
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
최선민
  • 13
  • 3
  • Shouldn't you address the "trash memory" thing first? – Scott Hunter Jul 23 '20 at 14:33
  • 8
    `scanf("%d",chnum);` -> `scanf("%d", &chnum);` (turn on compiler warnings!). – Paul R Jul 23 '20 at 14:34
  • 2
    `gets(str1);` is likely to cause a buffer overflow. Never use `gets`, it is no longer part of the standard C library. Please read [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) The buffer size is off-by-one too (for the null terminator). – Weather Vane Jul 23 '20 at 14:43
  • A better design for your `getstr` function would take the string length as a parameter, instead of relying on a global variable. – Robert Harvey Jul 23 '20 at 14:45

1 Answers1

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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74
  • Why did you declare chnum in size_t type in your answer and print it in %zu type? I tried to declare it as an int type and print it as %d, but it doesn't work. – 최선민 Jul 24 '20 at 03:23