Solved

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

Posted on 2004-10-06
14
213 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +4
14 Comments
 
LVL 45

Accepted Solution

by:
Kent Olsen earned 25 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 25 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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 45

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 45

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

Industry Leaders: 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

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them 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.

636 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