0

I have just entered the world of C programming, and I'm currently learning how to use malloc & free.

I've written a short excercise code to printf the string entered with scanf, and I am having trouble compiling it.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main(void)
{
    char *keyword;
    printf("keyword: ");
    scanf("%s", keyword);
    if (keyword == NULL)
        return 1;

    char *t = malloc(strlen(keyword) + 1);
    if (t == NULL)
        return 1;

    for (int i = 0, n = strlen(keyword) + 1; i < n; i++)
        t[i] = keyword[i];

    printf("t: %s\n", t);

    free(t);
    return 0;
}

To debug it, I wrote the same code but without the for loop(code below), and then the code worked well. This led me to conclude that the issue might be with the for loop which is used to assign characters to corresponding memory locations, but I am still unable to find a solution.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main(void)
{
    char *keyword;
    printf("keyword: ");
    scanf("%s", keyword);
    if (keyword == NULL)
        return 1;

    char *t = malloc(strlen(keyword) + 1);
    if (t == NULL)
        return 1;

    t[0] = keyword[0];
    t[1] = keyword[1];
    t[2] = keyword[2];
    t[3] = keyword[3];
    t[4] = keyword[4];
    t[5] = keyword[5];
    printf("t: ");
    printf("%c", t[0]);
    printf("%c", t[1]);
    printf("%c", t[2]);
    printf("%c", t[3]);
    printf("%c", t[4]);
    printf("%c", t[5]);
    printf("\n");

    free(t);
    return 0;
}

I am pretty sure this is a simple error, but I cannot figure out the reason of this error with debugger or online. I would really appreciate it if someone could help me solve this problem.

6
  • 4
    When you do scanf("%s", keyword), where does keyword point? What have your beginners material (courses, tutorials, teachers, books, etc.) said about scanf, its format specifiers and the corresponding arguments? Commented Jul 10 at 6:28
  • 2
    As for problems building the code, if you're a beginner and don't build with extra warning enabled, it would actually build, but you will likely have problems when running it. You need to always enable extra warnings (and really treat them as errors), because the compiler will tell you about your problem. Commented Jul 10 at 6:32
  • @Someprogrammerdude From what I've studied and understood, *keyword simply declares the pointer, but doesn’t allocate any memory. And I thought scanf would automatically calculate the size of string and allocate memory correspondingly(honestly, I absorbed just a few percent of these whole concepts, like pointer, memory allocation, or scanf, and I admit I need more study to understand them).
    – Woodrow
    Commented Jul 10 at 8:22
  • 1
    "I thought scanf would automatically calculate the size of string and allocate memory correspondingly" Unfortunately that's not really possible. No function in C, user-created or one of the standard functions, can modify its argument for the caller. Which of course means that the pointer passed to scanf can't be modified by the function. What it does is modify the memory where the pointer is pointing. Also, if you don't initialize a local variable its value will be indeterminate (look at it as garbage), which for your case means that keyword, might point anywhere. Commented Jul 10 at 8:51
  • 1
    @Woodrow scanf does not allocate memory. It expects to be passed valid addresses of buffers/variables.
    – wohlstad
    Commented Jul 10 at 9:01

3 Answers 3

4

The following lines:

char *keyword;
printf("keyword: ");
scanf("%s", keyword);
if (keyword == NULL)
     return 1;

Have several problems:

  1. keyword is not initialized. It must be initialized to point to some buffer/memory in order to scanf into it in scanf("%s", keyword);.
    Accessing it uninitialized causes undefined behavior (UB).
    In order to initialize it you should determine the maximum length you allow for it, and then initialize it by:
    (1) Using malloc
    (2) Using stack allocation (if the max size is relatively small)
    (3) Setting it to point to some existing buffer
    Don't forget to add 1 to the max length when you allocate, for zero termination.

  2. After determining the maximum length of keyword you should pass this value to scanf to make sure the buffer is not overrun, e.g.:

    ... = scanf("%33s", keyword);  // here the maximum length is 33
    
  3. You should always check the return value of scanf. If it succeeds it returns:

    Number of receiving arguments successfully assigned

    (here it should be 1).

  4. (keyword == NULL) is unlikely to be true (unless by chance), regardless of whether scanf succeeded or not. And if you'll initialize it properly as explained above, it will never be NULL.

0
1

and then the code worked well. ...
IT IS NOT Work well !!
It's just because of ... you are a lucky guy....

First of all, when you compile your code, you might get a warning message about this code :

char *keyword;
scanf("%s", keyword);

Because,

  1. You are NOT assign(initial) the value(pointer) of keyword.
  2. When the pointer of keyword is uncertain, you use it as the input pointer for scanf()

So, where to store the data from the input of 'scanf()' ?? It's uncertainly memory place !!

So, You are a lucky guy that not cause your program to crash...

Do NOT ignore warning message for all situation!

For your case, it's better to change it into :

char keyword[1048575];
scanf("%s", &keyword);

-or-

char *keyword = malloc(1048575);
scanf("%s", keyword);

Then, you might run into for lop smoothly.
~enjoy~

2
  • 1
    While one shouldn't be greedy with array sizes, 1048575 is a bit too much. More than a couple of hundred elements is just a waste of space. Commented Jul 10 at 7:02
  • @Someprogrammerdude Yeap, but he should find this issue out and adjust it by himself。
    – James
    Commented Jul 11 at 6:59
-1

You did not allocate memory for keyword, which sometimes may not cause an error, but it is essential to initialize a pointer. An uninitialized pointer can point to any location in memory, leading to undefined behavior and potentially modifying important memory.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.