C string from GetString() when strlen produces segmentation fault -
i running program in c. when run program segmentation fault error. in gdb when backtrace tells me
program received signal sigsegv, segmentation fault. __strlen_sse2_bsf () @ ../sysdeps/i386/i686/multiarch/strlen-sse2-bsf.s:51 51 movdqu (%edi), %xmm1
i believe has strlen.
the time use strlen is:
string s = getstring(); int stringlength = strlen(s);
when change strlen sizeof error stops.
what wrong code?
documentation of getstring
/* * reads line of text standard input , returns * string (char *), sans trailing newline character. (ergo, if * user inputs "\n", returns "" not null.) returns null * upon error or no input whatsoever (i.e., eof). leading * , trailing whitespace not ignored. stores string on heap * (via malloc); memory must freed caller avoid leak. */ string getstring(void) { // growable buffer chars string buffer = null; // capacity of buffer unsigned int capacity = 0; // number of chars in buffer unsigned int n = 0; // character read or eof int c; // iteratively chars standard input while ((c = fgetc(stdin)) != '\n' && c != eof) { // grow buffer if necessary if (n + 1 > capacity) { // determine new capacity: start @ 32 double if (capacity == 0) capacity = 32; else if (capacity <= (uint_max / 2)) capacity *= 2; else { free(buffer); return null; } // extend buffer's capacity string temp = realloc(buffer, capacity * sizeof(char)); if (temp == null) { free(buffer); return null; } buffer = temp; } // append current character buffer buffer[n++] = c; } // return null if user provided no input if (n == 0 && c == eof) return null; // minimize buffer string minimal = malloc((n + 1) * sizeof(char)); strncpy(minimal, buffer, n); free(buffer); // terminate string minimal[n] = '\0'; // return string return minimal; }
the description of getstring()
function states can return null on error or on eof.
if pass return value strlen()
without checking, program crash.
string s = getstring(); int stringlength = 0; if (s != 0) stringlength = strlen(s);
this @ least won't crash.
you might notice how confusion typedef char *string;
causes , how little benefit confers, , take heart. don't have repeat mistakes of teaching you.
i observe code fragment:
// minimize buffer string minimal = malloc((n + 1) * sizeof(char)); strncpy(minimal, buffer, n); free(buffer);
could better, , more simply, written as:
string minimal = realloc(buffer, n + 1);
to shrink allocation correct size.
Comments
Post a Comment