Question:
C programming using getchar()?
Travis
2010-11-26 20:49:27 UTC
char* user_name_ptr, user_name;

user_name_ptr = (char*)malloc(sizeof(char)*100);
user_name = user_name_ptr;

c = getchar();
while(c != '\n')
{
*user_name_ptr = c;
user_name_ptr++;
c = getchar();
}
*user_name_ptr = "\0";

printf("User_Name is: %s\n", user_name);


Other than the obvious security issues and bad code, what is wrong with this??
It Seg Faults... gdb backtrace shows that its segfualting when trying to printf()
Three answers:
Robc
2010-11-26 21:26:03 UTC
char* user_name_ptr, user_name;



should be:



char *user_name_ptr, *user_name;



When you define a pointer, the * goes with the variable name, not the type.



Doing:



char* user_name_ptr, user_name;



is equivalent to doing:



char* user_name_ptr;

char user_name;
2010-11-27 04:59:47 UTC
user_name is a single character, not a character pointer and you're printing it as a string, that's probably what's causing the seg fault providing this is only a snippet of code and not your entire program.



this is how i would write the program, if this is for a practical use and not an example of getchar()'s use:



#include

#include

#include



char *getstring()

{

char buffer[512];

char *ptr;



fgets(buffer, sizeof buffer, stdin);



/* Remove the trailing \n */

buffer[strlen(buffer) - 1] = '\0';



ptr = malloc(strlen(buffer));

strcpy(ptr, buffer);

return ptr;

}



int main()

{

char *user_name_ptr;



user_name_ptr = getstring();

printf("Username: %s\n", user_name_ptr);

return 0;

}
vmanes
2010-11-27 05:09:27 UTC
How about the fact you're using forward slash in your null terminator character, when it should be the backlash?



*user_name_ptr = "/0"


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...