strlen() not giving right value? [closed] - c

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 8 years ago.
Improve this question
#include "stdafx.h"
#include<string.h>
#include<stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
char abc[28] ;
//abc[26] = '\0';
abc[0]=65;
char hj = abc[0];
for(int i=0; i<26; i++)
{
abc[i]=++hj;
printf("%d\n",i);
}
int l=strlen(abc);
abc[l]='\0';
printf("length of abc_array is %d\n",(strlen(abc)));
for(int i=0; i<strlen(abc); i++)
{
printf("%c",abc[i]);
printf("\n");
}
}
The output length of the string is 39, which is wrong. What is the error?

you need to set abc[i] = '\0' before you call strlen.

Standard strlen function is only applicable to strings. String is a sequence of characters terminated by zero character. Passing something that is not a string to strlen results in undefined behavior.
What you are passing to strlen in your code is not a string. This is why you get meaningless results from strlen.

Related

Why does my free() function does not working(Code was given below) [closed]

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 5 years ago.
Improve this question
Please go to line 29 and read the comment.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* messenges[5];
char* allstrings;
register int i;
int total = 0;
for (i = 0; i < 5; i++)
{
printf("Enter a string: ");
messenges[i] = (char*)malloc(5 * sizeof(char));
scanf("%s", messenges[i]);
total += strlen(messenges[i]);
}
allstrings = (char*)malloc(total);
strcpy(allstrings, messenges[0]);
for (i = 1; i < 5; i++)
{
strcat(allstrings, " ");
strcat(allstrings, messenges[i]);
}
printf("%s", allstrings);
free(allstrings); // This does not work..WHY?(Visual Studio 2015)
for (i = 0; i < 5; i++)
{
free(messenges[i]);// This works fine.
}
getch();
return 0;
}
Above code doesn't free allstrings but it can free messenges[i]. Why doesn't it work for allstrings as well?
It probably fails because you seem to have forgotten that char strings in C are really called null-terminated byte strings. That null-terminator part is quite important, and it needs an extra byte or you will write out of bounds.
Writing out of bounds leads to undefined behavior, and might overwrite internal data used by the memory allocator leading free to "not work".
First of all strings in c are null terminated char array. You didn't allocate enough space to store them. Also you didn't allocate enough space for those blanks you have concatenated. Long story short by writing to memory that is not allocated by you has invoked undefined behavior.
Also it is not clear how you can say that free() call failed. What is your idea of not freeing the memory?
In this case for example, you can consider two things which will help you allocate enough memory. strcat and strcpy both take into account the \0 and also strcat overwrites the \0 in the source string.
Also there are many many problems in your code - starting from not allocating enough memory - casting the return value of malloc, not chekcing the return value of malloc and using scanf without length modifier.

Segmentation fault in C [closed]

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
Basically I want to get user's input and tokenize it. For example I type
4 <tab> 5 <tab> 6
I want to get just
4
5
6
But my piece of code does not work ;(
#include <stdio.h>
#include <string.h>
int main ()
{
char str;
scanf("%c",&str);
char *p = strtok(str, "\t");
while(p != NULL) {
printf("%s\n", p);
p = strtok(NULL, "\t");
}
}
You are getting mixed up between char and char*.
Try this instead:
#include <stdio.h>
int main ()
{
char str[1000];
while(scanf("%s", str)) {
printf("%s\n", str);
}
}
1000 is the maximum length of a single token. Adjust as necessary.

Program to read input lines of any length in C [closed]

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
And I want it to print to output as is. Curently I am using this code
#include <stdio.h>
#include <ctype.h>
#define BUFFER_SIZE 2000
int main(void)
{
char buffer[BUFFER_SIZE];
while(fgets (buffer, BUFFER_SIZE, stdin) !=NULL)
{
printf("%s",buffer);
}
return 0;
}
Then I want the program to be able to skip html tags in the original text but I don't know exactly how to work around that.
You should use getline(3) (at least on Posix compliant systems). Your fgets based code won't work with very long lines (because a very long line would be "truncated": all of it would be read, but only BUFFER_SIZE characters would have been copied, and the rest of the line ignored).
You could code
char* linebuf=NULL;
size_t linesize=0;
while (!feof(stdin)) {
ssize_t linelen = getline(&linebuf, &linesize, stdin);
if (linelen<0) { perror("getline"); exit(EXIT_FAILURE); };
fputs(linebuf, stdout);
}
In the above code, the linebuf will (unless failure) be grown to the widest line size. You should free(linebuf) after that loop...

what is the use of %.*s in this program [closed]

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 have the following program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
static char string[12];
int length,c,d;
printf("Enter a string :");
gets(string);
length=strlen(string);
printf("\nLength of the string is %d",length);
for(c=0;c<=length-2;c++)
{
d=c+1;
printf("\t%.*s\n",d,string);
}
for(c=length;c>=0;c--)
{
d=c+1;
printf("\t%.*s\n",d,string);
}
}
I am very much confused about the usage of %.*s in the printf statement. I know %s is used for displaying strings, but I am confused the usage of .* before s in this program. Also there is only one datatype (%s) mentioned inside the quotation marks in the printf statement, but there are two variables mentioned in the printf statement.
It is a precision component, which specifies maximum number of bytes for string conversions. Asterisk (*), uses an integer argument, which specifies the value (for precision) to be used.
As an example, the following code:
#include <stdio.h>
int main(int argv, char **argc)
{
char *s = "hello, world";
printf("%.*s\n", 4, s);
return 0;
}
gives output:
hell
The format statement can allow a width and precision value. So, to print a string for a variable length then specify printf("%.*s", length, string). The length is substituted for the asterisk.

Why will this simple C program not run? [closed]

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
This code will not run. Can somebody tell me why?
#include <stdio.h>
#include <string.h>
main (){
char user[7];
printf("Username\n");
scanf("%s",user);
if(user == 'admin'){
printf("Hello World");
}else{
printf("Bad");
}
return(0);
}
This is a working example. You need to use strcmp to compare strings. strcmp() returns 0, if the strings are equal.
If the max input length is known, then you should also use length specifier in scanf or one of the suggestion listed here, to prevent a buffer overflow.
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv)
{
char user[7];
printf("Username:\n");
scanf("%6s", user);
if(!strcmp(user, "admin"))
{
printf("Hello World");
}
else
{
printf("Bad");
}
return 0;
}
This is not working because you are comparing two strings the wrong way. You need to use strcmp. Check this answer to see what strcmp returns in C.
To make your program work, change the line
if (user == 'admin')
to
if (strcmp (user, "admin") == 0)
Also, using scanf might be a bit dangerous, in rare cases. I prefer using fgets for strings. To use fgets, do:
fgets (user, sizeof (user), stdin);

Resources