Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2004-10-06
14
Medium Priority
?
217 Views
Last Modified: 2010-04-15
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?
0
Comment
Question by:nofearse
  • 3
  • 3
  • 2
  • +4
12 Comments
 
LVL 46

Accepted Solution

by:
Kent Olsen earned 100 total points
ID: 12242279

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
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 100 total points
ID: 12242307
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
 
LVL 23

Expert Comment

by:brettmjohnson
ID: 12242326
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 5

Expert Comment

by:libin_v
ID: 12245403
I think the scanf statement should be

scanf("%u%s", &num, aString);
0
 

Author Comment

by:nofearse
ID: 12245914
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
 
LVL 23

Expert Comment

by:brettmjohnson
ID: 12250145
> 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
 
LVL 12

Expert Comment

by:stefan73
ID: 12260517
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
 
LVL 1

Expert Comment

by:manojantony
ID: 12278080
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
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12278735
Hi  manojantony,

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


Kent
0
 
LVL 1

Expert Comment

by:manojantony
ID: 12279648
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
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 12279719

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

Kent
0
 
LVL 1

Expert Comment

by:manojantony
ID: 12279855
Ye u r right.  I agree.. its fine .. for that particular example. :-)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
Suggested Courses

783 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question