I am new to C and facing an odd behavior when using malloc.
I read a input text from stdin (fgets) and pass it to a function myfunction.
void myfunction(char* src) {
printf("src: |%s|\n", src);
int srcLength = strlen(src);
printf("src length: %d\n", srcLength);
// CAUSES ODD BEHAVIOR IN MY SITUATION
// char* output = malloc(200);
//
// if (output == NULL) {
// exit(EXIT_FAILURE);
// }
for (int i=0; i < srcLength; ++i) {
char currChar = src[i];
printf("|%c| ", currChar);
}
}
When executing the function without malloc (see comment), I am getting this:
src: |asdf|
src length: 4
|a| |s| |d| |f|
But with malloc, I am getting this awkward behaviour. As if there were no chars in the char*:
src: |asdf|
src length: 4
|| || || ||
There might be an issue with the char* src (from stdin). But I am unsure because the input string is printed correctly (src: |asdf|
).
Can anybody support me, how to analyze the source of the problem?
UPDATE 1:
Here is the code for reading from stdin and invoking myfunction.
int main(int argc, char **argv) {
char *input = NULL;
input = readStdin();
myfunction(input);
return EXIT_SUCCESS;
}
char* readStdin(void) {
char buffer[400];
char *text = fgets(buffer, sizeof(buffer), stdin);
return text;
}
The myfunction
and readStdin
are in different files, but I hope it does not matter.
UPDATE 2:
As proposed by the supporters in the comments, I did a resolution of the scope issue.
I changed the function prototype of readStdin
to:
char* readStdin(char* input);
And I invoke readStdin
with the allocated input
.
char* input = malloc(400);
In readStdin
I replaced buffer
with the function parameter.