• C

How to print the value of a char* type data in C

i have something like:
unsigned int num = 0;
char* aString = "aaa";

printf("enter data: \n");
scanf("%u%s", &num, &aString);
printf("%u\t%s\n", num, aString);

it doesnt work, gives segmentation fault on gcc
How can i fix it?
nofearseAsked:
Who is Participating?
 
Kent OlsenData Warehouse Architect / DBACommented:

This is a popular subject here.  :)

Your code is:

unsigned int num = 0;
char* aString = "aaa";

printf("enter data: \n");
scanf("%u%s", &num, &aString);
printf("%u\t%s\n", num, aString);


However, you don't really have a read/write buffer associated with aString.  You've initialized aString to point to a constant, which the compiler and linker put into "read only memory".  Now when you execute the scanf() function, it attempts to write to the address specified by aString, which is that pesky location in "read only memory".

Make a small change and you'll get past this:

unsigned int num = 0;
char aString[20];

printf("enter data: \n");
scanf("%u%s", &num, &aString);
printf("%u\t%s\n", num, aString);


Good Luck,
Kent
0
 
grg99Commented:
aString is a char *, you're trying to store input characters into it.  Not good.

You need to either do:

aString = malloc(1000);   to set the pointer to point to some real memory.

or declare  char aString[1000];   to make it an actual array of char.

As a POOR substitute you couls pass aString instead of &aString to scanf,
but this would store your input over some place in memory where the compiler
keeps the constant string "aaa".  Not too keen either!

C gives you such a wide variety of ways of shooting yourself in the toe.



0
 
brettmjohnsonCommented:
The scanf() will attempt to write a sequence of chars to the 4 bytes of memory
currently occupied by the POINTER to "aaa".  There are several things wrong with this:

1) scanf("%s") expects a pointer to char.  You are passing a pointer to a pointer to char.  
You have made one of two possible common errors:
 a) You were trying to have scanf() store the input data into the bytes of memory
     currently occupied by "aaa".  See items 2 and 3 below.
 b) You were expecting scanf() to return a pointer to new or existing memory
     that holds the string, modifying the pointer (aString) to point to that new location
     (and no longer point at "aaa").  See item 4 below.

2) If the user enters more than 3 characters, the input will overflow the 4 bytes
[or 8 bytes - depending on sizeof(pointer) for your platform] overwriting adjacent data.

3) String constants may be (but are not required to be) stored in read-only memory.
Attempting to write into read-only memory will yield a segmentation fault.

4) scanf("%s") expects a pointer to an array of char large enough to hold the expected
input.  You should consider declaring aString as:   char aString[1024];
The char array will be mutable and sufficiently large to accept most input.
You can also limit the number of bytes read into aString by specifying a width
to the field read:
scanf("%u%s", &num, &aString);

0
KuppingerCole Reviews AlgoSec in Executive Report

Leading analyst firm, KuppingerCole reviews AlgoSec's Security Policy Management Solution, and the security challenges faced by companies today in their Executive View report.

 
libin_vCommented:
I think the scanf statement should be

scanf("%u%s", &num, aString);
0
 
nofearseAuthor Commented:
What if I don't know what size the maximum length of the string is
Does C has INT_MAX or something, just like C++?
0
 
brettmjohnsonCommented:
> What if I don't know what size the maximum length of the string is
> Does C has INT_MAX or something, just like C++?

Yes, INT_MAX is in the ANSI C spec.  However, it sounds like you are contemplating
something like  char buffer[INT_MAX];  which would be a 2 gigabyte buffer - unwise.

Typically, users of scanf() create a "sufficiently large" buffer  (in my example, I used
1 a kilobyte buffer, however 2, 4, 8 and 16 kilobyte scratch buffers are not uncommon.
The wise programmer will also use input functions that avoid overflowing the input
buffer, like fgets() or a field width specification for scanf().

0
 
stefan73Commented:
Hi nofearse,
> What if I don't know what size the maximum length of the string is
> Does C has INT_MAX or something, just like C++?
That's a classic security problem: buffer overflow. Never, ever use a function which does not limit the input size. Even if your program isn't security-sensitive, it will be much more stable when you use fgets() instead for your string.

Cheers!

Stefan
0
 
manojantonyCommented:
i think fgets and sscanf combination will work

char * aString, * buffer;
aString = (char *) malloc(MAX_LEN + 2);
do {
       if (!fgets(buffer, MAX_INPUT_LEN + 2, stdin))
      return 0;
       if (sscanf(buffer, "%s", aString) != 1)
      continue;
     }
while (1);
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi  manojantony,

While are you doing a sscanf() here?  strcpy() is faster and more straight-forward.


Kent
0
 
manojantonyCommented:
Kent,

Its for input validation..

if (sscanf(buffer, "%s", aString) != 1)
                                                  ^
if (sscanf(buffer, "%d%d%d", aString) != 3)
                                                            ^
hope you got the point

-
MA    
0
 
Kent OlsenData Warehouse Architect / DBACommented:

Ok, but in your example I believe that you will always return 1.

Kent
0
 
manojantonyCommented:
Ye u r right.  I agree.. its fine .. for that particular example. :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.