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.
scanf("%s", keyword)
, where doeskeyword
point? What have your beginners material (courses, tutorials, teachers, books, etc.) said aboutscanf
, its format specifiers and the corresponding arguments?*keyword
simply declares the pointer, but doesn’t allocate any memory. And I thoughtscanf
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, orscanf
, and I admit I need more study to understand them).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 toscanf
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 thatkeyword
, might point anywhere.scanf
does not allocate memory. It expects to be passed valid addresses of buffers/variables.