arrays - Method to safely get a string in C -
i'm new c , want write function safely prompts user string , returns it. while think have safety part handled, can't return string main method , print out. here code
//method safely read user input char * getfilename(char* filename) { char* str[50]; int isvalid = 0; while (isvalid == 0) { isvalid = 1; printf("enter file name: "); fgets(str, 50, stdin); if (strlen(str) == 49 && str[48] != '\n') { //http://stackoverflow.com/questions/21691843/how-to-correctly-input-a-string-in-c isvalid = 0; if (strlen(str) > 0 && str[strlen(str) - 1] != '\n') {//http://stackoverflow.com/questions/35136026/simple-loops-and-string-length-in-c?noredirect=1#comment58000759_35136026 printf("error! string long\n\n"); { fgets(str, 50, stdin); } while (strlen(str) > 0 && str[strlen(str) - 1] != '\n'); } } (int = 0; < strlen(str); i++) { if (str[i] == '%') { printf("error: attempted string format attack\n\n"); isvalid = 0; } } } (int = 0; < strlen(str); i++) { filename[i] = str[i]; } return filename; } int main() { //opening text file char filename[50]; getfilename(filename); printf(filename); printf("press enter continue..."); getchar(); // return 0; } running code prints result
and have no idea why. appreciated!
because never copy null terminator. this
for (int = 0; < strlen(str); i++) filename[i] = str[i]; only copies characters, not null terminator. use strcpy() since included string.h overuse strlen().
try this
int i; (i = 0; str[i] != '\0' ; ++i) filename[i] = str[i]; filename[i] = str[i]; and should work expect it, , avoid using strlen() that.
you have major problem,
char *str[50]; is array of 50 char pointers, , doesn't seem want instead
char str[50]; your code complicated , hard understand, think want
#include <stdio.h> #include <string.h> char * getfilename(char *str, size_t size) { int isvalid = 0; while (isvalid == 0) { size_t length; isvalid = 1; printf("enter file name: "); if (fgets(str, size, stdin) == null) return null; length = strlen(str); if ((length == size - 1) && (str[size - 2] != '\n')) { isvalid = 0; if ((length > 0) && (str[length - 1] != '\n')) { printf("error! string long\n\n"); continue; } } if (strchr(str, '%') != null) { printf("error: attempted string format attack\n\n"); isvalid = 0; } } return str; } int main() { char array[100]; if (getfilename(array, sizeof(array)) == null) fprintf(stderr, "error: input problem?\n"); else printf(array); return 0; } 
Comments
Post a Comment