开发者

Problem with scanf() on mac

I compile a C library on mac os x. When I typed the input and after printing on the screen the 开发者_JS百科data I don't see something.

char *path = NULL;
peerdisplay = "Bob";
printf("Insert the full 'To' path: ");
scanf(" %a[^\n]", &path);
printf("A path: %s \n", &path);

When I replace the %a to %s, the printing ok, but after the running I have a segmentation error. I like to running such as script.


%a is gnu-specific non-standard extension to scanf grabs. What says your OS X manpages about it ?

The GNU C library supports a non-standard extension that causes the library to dynamically allocate a string of sufficient size for input strings for the %s and %a[range] conversion specifiers. To make use of this feature, specify a as a length modifier (thus %as or %a[range]). The caller must free(3) the returned string

^is that your intent ?

in that case, be aware that

The a modifier is not available if the program is compiled with gcc -std=c99 or gcc -D_ISOC99_SOURCE (unless _GNU_SOURCE is also speci- fied), in which case the a is interpreted as a specifier for floating- point numbers (see above).


You need to allocate memory for path. It needs to be enough memory for whatever bytes will be entered, plus the NULL terminating byte.


Your path is a null pointer, make it point to some allocated memory large enough to hold the string to be read and the terminating null char.

You should not be passing address of path to scanf and printf, instead pass path itself.

Since you are scanning a string use %s instead of %a


First of all, if you pass a null into scanf as you're doing here, you're basically telling the c library to copy whatever string is entered into null space (aka the first page of memory, usually protected against writing for just this reason). Secondly, %a is supposed to match a floating point number, not a string. Third, it might be a good idea to actually read the documentation for a library function before you start calling it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜