Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an array of integers, for example:
I memcpy the value into a char buffer, and the next time I retrieve it, it becomes a binary value, for example, 00000 -> 16. How do I avoid this?
Here is a snippet of my code:
char buf[BUFSIZE];
int outgoingPorts[4] = { 100000, 100001, 100002, 100003 };
memcpy(buf, &outgoingPorts[0], sizeof(outgoingPorts[0]);
printf("Port no: %i\n", buf);
Here, buf or the first outgoing port is 16 instead of 10000.
First of all, you're using wrong format specifier altogether, for the content of a char pointer to be printed, you need to use %s, provided that char array in null-terminated. Otherwise, you'll face undefined behaviour.
Then, if you really want to store an int value in a char array, the most suited way to go is to make use of snprintf() to print that value in the char array. Maybe the following pseudo-code will help you
char carr[16];
snprintf(carr, 16, "%d", outgoingPorts[0]);
printf("%s\n", carr); //should print 100000
FWIW, using wrong or mismatched format specifier invokes undefined behaviour.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I seem to be unable to understand why do these two cases behave differently:
const char* TEXT = "hello world!";
int length = (int) strlen(TEXT);
char* array[length];
this is ok, however this one:
char* text;
scanf("%[^\n]s", text);
// input "hello world!" and press enter
int length = (int) strlen(text);
char* array[length];
ends with a segmentation fault
what am I missing?
For the scanf call, text parameter, you do not allocate any memory. You also do not initialize the variable to a value. This results in scanf writing to random memory, which causes your segmentation fault.
To fix this issue you need to allocate a buffer of a reasonable size:
char* text = malloc(1024);
1024 is the maximum size that you expect the input data to be. This, however, still leaves the code vulnerable to buffer overflows. To prevent buffer overflows you can inform scanf that text is of a certain size; look for the answers here
If you do not want to allocate the memory yourself, scanf can do it for you:
Note that the POSIX 2008 (2013) version of the
scanf()
family of functions supports a format modifier m (an
assignment-allocation character) for string inputs (%s, %c, %[).
Instead of taking a char * argument, it takes a char ** argument,
and it allocates the necessary space for the value it reads:
char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
printf("String is: <<%s>>\n", buffer);
free(buffer);
}
If the sscanf() function fails to satisfy all the conversion
specifications, then all the memory it allocated for %ms-like
conversions is freed before the function returns.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
char key, vector;
char plainText[101];
char cipher;
int i, cipherValue;
int keyLength, IVLength;
scanf("%s", key);
scanf("%s", vector);
return 0;
}
My program crashes after I input values for the scanf parts. I don't understand why.
The problem with
scanf("%s", key);
scanf("%s", vector);
is:
key and vector are of type char, not pointers to char. The can hold one character only.1
With %s scanf expects a pointer to char. As it stands right now, you
are passing uninitialized integer values as if it were pointers, that's
undefined behaviour and your program crashes as a result of it. The compiler
must have given you a warning about this, don't ignore the compiler's warnings,
they are there to help you, not annoy you.
The correct version:
char key[101], vector[101];
...
scanf("%s", key);
scanf("%s", vector);
// or to limit the number of bytes
// written in the buffer, as pointed out
// in the comments by user viraptor
scanf("%100s", key);
scanf("%100s", vector);
For more information about scanf, please read the documentation
Footnote
1A string in C is a sequence of characters that ends with the
'\0'-terminating byte. A string with one single character needs a char array
of dimension 2 or more. In general, a char array of dimension n can store
strings with maximal length of n-1. You have to keep that in mind when passing
pointers to char to functions when they expect strings. A pointer to a single
char will lead to undefined behaviour because it overflows.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This program accept 5 string and print them.
here is the program:-
#include"stdio.h"
#include"conio.h"
void main(){
clrscr();
char s[5];
for(int i=0;i<5;i++){
scanf("%s", s[i]);
}
for(i=0;i<5;i++){
printf("\n\n%s", s[i]);
}
getch();
}
when i execute this program the output will be this
Click here to see the output of the program
but when i enter the string in different way it print wrong output
Click here to see the output of the program
You are reading a string into a char, or rather, the string you read starts at the char position i in s. As s is very short (and when i is 5 it is empty), there will be an overflow, causing undefined behavior.
You want to have an array of strings, not of chars, as Blue Pixy mentions in his comment, e.g. char s[5][32];.
Also turn warnings on. The i in the second for loop is not defined.
You've declared s as a 5-element array of char; each s[i] can store a single character value, not a string. Since you don't explicitly initialize each s[i], they contain an indeterminate value.
The argument corresponding to the %s specifier in scanf must have type char * (each s[i] has type char), and it must point to the first element of an array of char large enough to store the string contents (including the 0 terminator that marks the end of the string).
When you call
scanf( "%s", s[i] );
you're telling scanf to store the next sequence of non-whitespace characters to the address corresponding to the value stored in s[i], which is a) indeterminate and b) likely not valid. The resulting behavior is undefined, meaning pretty much anything can happen - your code may work as expected, it may crash outright, it may give you garbled output, it may corrupt other data, etc.
As written, s can store a string up to 4 characters long.
If you want to store an array of strings, then s needs to be a 2-dimensional array of char:
#define MAX_STRING_LENGTH 20 // or however long you expect your longest string to be
...
char s[5][MAX_STRING_LENGTH + 1];
Each s[i] can now store a string up to MAX_STRING_LENGTH characters. The rest of your code should now behave as expected.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm having a pretty hard time working on this assignment I have for one of my CSC classes. I am making a character array from my name (ie John Doe). I need to pass a pointer of my character array into a function that outputs the number of characters stored in your character array. Then I need the function to also return this integer back to my main function.
If anyone would like to help me in advanced
I need to spell it completely backwards. i.e. (eoD nhoJ)
I need to inform the user of which element of my array the space in there name is. I also need to return this value as well.
Then last but not least I need to reverse the name i.e. (Doe John)
Please help me with this. I've only posted the part of the assignment I've actually managed to figure out. Thank you all in advance.
#include <stdio.h>
#include <string.h>
int main ()
{
char name [25]={'\0'};
fgets(name,sizeof(name),stdin);
printf("You Entered: %s \n", name);
printf("There are %u characters. \n", strlen(char * name));
}
strlen(char * name) ==> strlen(name)
You should not use char * before string while calculating length
EDIT
If your intention is to write your own function for some practice.
declare function
unsigned int my_strlen(char *); //argument needed is character pointer
And define
unsigned int my_strlen(char *str)
{
//find length..
return length;
}
Function call
printf("There are %u characters. \n", my_strlen(name)); // passing starting address of character array to a function.
Here also you should not use char * before name.
All your questions can easily found on Google. just doing simple search you can found.
If you want to do them by your self. you need to read c tutorials.
Change:
printf("There are %u characters. \n", strlen(char * name));
by:
printf("There are %u characters. \n", strlen(name));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing a program in which stdin is read into a buffer, then processed. The vast majority of these items that need to be processed are strings (or well, character arrays). However, I do have one item that needs to be read in as a character array and then converted to int for ease of use in the future.
for(i=0; i<n; i++){
num[i] = buff[(i)];
printf("%c", num[i]);
}
convert = atoi(num);
So I know for sure that the correct group of characters is being read into num because the printf for that is correct. However, when I try to print convert I end up getting 0, and I'm very perplexed as to what I'm doing wrong. I know that the 0 return means that a valid conversion could not be performed, but I don't know what's making it invalid. Any tips?
EDIT: Sorry for not including these before >_<
n is the number of chars in the buff array
buff is the buffer array stdin is read into
atoi is a function that gives you no means to analyze error conditions. On top of that, it produces undefined behavior in overflow situations. Don't ever use atoi (or atof or anything from ato... group) in real-life programs. It is practically useless.
To perform string-to-number conversions use strtol (and other functions from strto... group).
Now, what is inside your num at the moment you call your atoi? Is your num properly zero-terminated?