BaluEdo
BaluEdo

Reputation: 119

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 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.

Upvotes: 3

Views: 2875

Answers (4)

PypeBros
PypeBros

Reputation: 2646

%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).

Upvotes: 3

Paul Tomblin
Paul Tomblin

Reputation: 182832

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.

Upvotes: 1

codaddict
codaddict

Reputation: 455360

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

Upvotes: 1

wadesworld
wadesworld

Reputation: 13763

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

Upvotes: 2

Related Questions