简体   繁体   中英

What's the difference between a string and a user entered string in C

I'm using with a smaller piece of code to test functionality for a larger (beginner) program, but I don't understand the difference between two strings.

I found and used:

#include <stdio.h>
#include <string.h>

int main()
{

char *string, *found;

string = strdup ("1/2/3");
printf("Orig: '%s'\n",string);

while ((found = strsep(&string,"/")) != NULL )
  printf ("%s\n",found);

return (0);
}

and this print the tokens one at a time.

Then when I try and move to a user entered string:

#include <stdio.h>
#include <string.h>

int main()
{
  char string[13],
  char *found, *cp = string;

  fprintf(stderr, "\nEnter string: ");
  scanf("%12s",string);
  printf("Original string: '%s'\n",string);

  while((found =  strsep(&cp,"/,-")) != NULL )
    printf("%s\n",found);

  return(0);
}

I get a seg fault. I understand the basics of pointers, arrays and strings, but clearly I'm missing something, and would love for someone to tell me what it is!

Also - if I change printf("%s\\n",found); to printf("%i\\n",found); I get some junk integers returned, but always the correct amount, eg If I enter 1/2/3 I get three lines of integers, 1111/2222 I get two lines.

Thanks!

-Edit- There was an adittional problem with strsep , detailed here . Thanks all.

In the first piece of code, string is assigned the return value of strdup , which allocates space for the string to duplicate and returns a pointer to that allocated space.

In the second piece of code, string uninitialized when it is passed to scanf , so scanf is reading the invalid value in that pointer and attempting to dereference it. This invokes undefined behavior which in this case manifests as a crash.

You need to set aside space for the user's string. A simple way to do this is to create an array of a given size:

char string[80];

Then tell scanf how many characters it can read in:

 scanf("%79s",string);

Differences between the two cases:

  1. In the first case string points to valid memory that was allocated by strdup while in the second case you are trying to read into invalid memory.

  2. The first case is well behaved while the second case is cause for undefined behavior.

The second case can be fixed by allocating memory for it using malloc or using a fixed size array.

char *string,*found;
string = malloc(100); // Make it large enough for your need.
fprintf(stderr, "\nEnter string: ");
scanf("%99s",string);

or

char string[100], *found;
fprintf(stderr, "\nEnter string: ");
scanf("%99s",string);

Make sure you deallocate dynamically allocated memory. Otherwise, your program leaks memory.

You should allocate memory for the user input string.

First option is statically

char string[256];

and second option is dynamically using malloc() function

char *string;

string = (char*) malloc(256 * sizeof(char));
if (string == NULL)
   {
   //error
   }

Don't forget at the end to release the allocated memory

free(string);

You didn't allocate the space needed ! You have to have a memory space to write to. You can have it statically "char string[256]", or dynamically with allocation.

In your first example, you use "strdup" that does a malloc, but scanf will not allocate memory for you.

If you want all the user input, you usually wrap the scanf in a while loop in order to retrieve the user input chunk by chunk. Then you have to reallocate each time your buffer is insuffisante to add the chunk.

If you just want to retrieve a string from stdin without doing any format-checking, I strongly recommand fgets.

The reason is very simple. Your string variable is a char pointer and you need to allocate memory to it to store a string.Probably in your first case strdup ("1/2/3"); returns a string and your char pointer *string points to the string return by strdup function and that is the reason why you are not getting the segmentation error in the first case. Even in your first case also you might get a segmentation error if enter a very long string.

so allocate enough memory to the string pointer like below in your second example and that will fix your problem:-

 char *string = malloc(50);// here malloc will allocate 50 bytes from heap

In user enter string case you do not have memory allocated to the pointer string.In the first case, strdup is allocating memory for string pointer while in the second case you do not have any memory associated with string pointer leading to segfault. first, allocate memory using malloc and then use scanf .

char string[13] char cp=string

Here cp is a variable of type char and as 1 byte of memory allocated

It won't be able to store a char array of 13 character which would be 13 bytes, and it's because of this you are getting segmentation fault

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM