In the following c code the 'line 10' doesn't print anything when ln8 & lb9 are removed. It just takes the input and prints nothing. But the weird thing is on addition of those 2 lines, the code works perfectly fine i.e the input string got printed twice once by for loop and once by the printf statement in ln10. (What i am trying to do is just print the input String)
I use MinGw Compiler and ran code using cmd.enter image description here
int main()
{
char *s;
scanf("%s",s);
printf("Line 9:\t");
for(int i=0;s[i]!='\0';i++) //line 8
printf("%c",*(s+i)); //line 9
printf("\nLine 12:\t%s\n",s); //line10
return 0;
}
char *s
you declare a pointer but do not allocate for it. It's undefined. Because the undefined behavior, everything can happen. (for example, When i test your program in my PC, it raises Segmentation fault (core dumped)
You have to allocate for the pointer before scanf (do not forget to free s when you do not need to use it):
char *s = malloc(sizeof(char) * MAX_LEN); // MAX_LEN: you define its value.
Or you can use the array of character:
char s[100]; // here, the string length is up to 99;
Try initializing the s using strdup.
int main()
{
char *s = strdup("");
scanf("%s",s);
printf("\nLine 12:\t%s\n",s); //line10
return 0;
}
Related
The code is supposed to print out 13:Hello World!, but the output is only 13:.
#include <stdio.h>
int main(){
char *str = "Hello World!\n";
int Laenge= 0;
while (*str++){
++Laenge;
}
printf(" %d:%c\n", Laenge, *str);
return 0;
}
You set str to point to the beginning of the string, and then you increment str till you get to the end. By that time, str is now pointing to the end of your string.
Try using a different pointer to walk through your string, or just save a copy of the pointer for later use.
It also looks like you're syntax is wrong for the print statement. I haven't coded in C for decades. I'm a Python user now. But I think *str would reference one char, and you want to reference the entire string. So if str was not corrupted, use %s and str instead of %c and *str in your printf().
You can interate till you find the null character!
#include <stdio.h>
int main()
{
char *str = "HELLO WORLD!\n";
int len = 0;
while(*(str + len) != '\0'){
len++;
}
printf("%d:%s", len, str);
return 0;
}
Your code is not working because your are incrementing the original string and converting it to '\0'. Use a walker.
you need to remeber the original str pointer
you should printf str not *str
#include <stdio.h>
int main(){
char *str = "Hello World!\n";
char *temp = str;
int Laenge= 0;
while (*temp++){
++Laenge;
}
printf(" %d:%c\n", Laenge, str);
return 0;
}
The code is only supposed to do what it has been programmed to do, to the letter of the law. Unfortunately, what's written doesn't always coincide with what the programmer intended the program to do.
In the while loop, you increment str until you reach the end, at which point the while loop ends. Now the pointer points to the end of the string.
Other than that, the format specifier for a string is %s, not %c. The %c would only print a single character. Change *str to str, unless you want to print a single character, but then you mentioned the expected output is supposed to be Hello, World.
Note:
Do not post text as an image. Post text as text, one can't copy and paste your code from an image. It's difficult to see where the problem may be arising from, and hence is difficult to debug.
maybe it's a dumb question but I'm new in C. I'm trying to return a pointer from a function using malloc. I made an array with strtok. Here it's the code of the function from which I'm trying to return the pointer:
int *data(){
int longi=0, *array=(int *) malloc(4 * sizeof(int));
char buffer[1024];
char *aux;
printf("Enter if approved(A) or failed (F) separated by a comma \",\": \n");
fgets(buffer,1023,stdin);
aux=strtok(buffer, ",");
while(aux)
{
array[longi]=aux;
longi++;
aux=strtok(NULL, ",");
}
printf("%s", array[0]);
return array;
}
And here is my main function:
int main(){
int *arr=data();
printf("%s",arr[0]); /*segmentation error */
return 0;
}
The segmentation fault occurs because you are trying to print part of your array as a string (%s). When using %d or %c (with char casting) it does not give that error.
However, it still doesn't make sense, since you are trying to put a pointer to the beginning of a string inside an array of integers. I'd suggest allocating an array of characters instead of integers, and making sure you've got a single character inside aux, then adding it to the array. You also need to make sure you don't accept more than 4 different characters, otherwise you might still have a buffer overflow.
printf when flag is %s is trying to read string from allocated memory, you giving an integer so this why it gives a segfault
replace array[longi]=aux; with array[longi]=atoi(aux); atoi will convert from string to integer, and for both printfs replace %s with %d
Total C noob here. I know there is something wrong with my sprintf_wrapper method because before I introduced it everything was working fine. The point of the function is to take a string buffer and a number and change the string buffers value to "WHALE=[num]". I then use this new string with putenv method.
The code results in "Segmentation fault (core dumped)", I believe it occurs after sprintf_wrapper is called.
Main Method
int main(void) {
getP0Info();
putenv("WHALE=7");
forkProcesses();
int whale = atoi(getenv("WHALE"));
char new_env[50];
sleep(1);
printf("P0: %d\n", whale);
whale = whale - 1;
sprintf_wrapper(new_env, whale);
putenv(new_env);
return 0;
}
sprintf_wrapper
void sprintf_wrapper(char* str, int num) {
char buffer[10];
str = "WHALE=";
sprintf(buffer,"%d", num);
strcat(str,buffer);
}
You're assigning a string constant to the str variable, then attempting to to append to it. Because string constants typically live in read only memory, this commonly causes a core dump.
Do this instead:
void sprintf_wrapper(char* str, int num) {
sprintf(str,"WHALE=%d", num);
}
sprintf_wrapper(new_env, whale);
You are appending to a string literal, which is read-only memory.
This generates a segmentation fault because you write into memory that is not supposed to be written into.
str = "WHALE=";
Thats a read only string literal.
I'm watching a course online learning C and I stumbled upon something that is crashing my program.
In the video they show the following code snippet :
#include <stdio.h>
int main()
{
char* ch;
int num = 12345;
sprintf(ch, "%d", num);
printf("%s\n", ch);
return(0);
}
I've decided to make my own little program and test it.
Here's the code I've written :
#include <stdio.h>
#define A 65
int main()
{
int n = A;
printf("n is equal to %d\n", n);
n = atoi("10");
printf("n is equal to %d\n", n);
char* ch;
sprintf(ch, "%d", n);
printf("ch is equal to %s\n", ch);
return 0;
}
When I run my program, the output is as follow :
n is equal to 65
n is equal to 10
After this part my program crashes.
I assume the sprintf function is causing this but I'm not sure why, I'm new to the language so I wouldn't know, I think I've done everything correctly judging by the code snippets that was shown in the video.
Could someone please explain me what I did wrong ?
Thanks in advance.
In the video they show the following code snippet: [...]
If this is a snippet that they say should work, stop watching that video: the snippet has undefined behavior, there is no chance that it would work properly unless by an unlucky coincidence.
I've decided to make my own little program and test it.
Your program has the same exact problem: the buffer to which sprintf is writing has not been initialized. Change the declaration of ch to allocate some space to it, like this:
char ch[20];
This will prevent your code from writing to memory pointed to by an uninitialized pointer, fixing the undefined behavior.
Could you explain to me how char* could be used?
If you would like to use char*, assign it a result of malloc of a proper size, and free the result at the end:
char *ch = malloc(20);
... // Put the rest of the code here
// Add this line before the end:
free(ch);
You need to alocate memory for ch or else use an array instead of a pointer.
char* ch = malloc(sizeyouwant * sizeof(char));
Where sizeyouwant is the number of characters you will store.
The problem is here:
char* ch;
this is just a char pointer, it needs to point to allocated memory to hold the string:
char ch[32];
I want to calculate length of string and copy the string to another without using c library function, but when I use fgets() function to read the string from keyboard, the code not showing the actual value of length as well as the destination string. I use the fgets() function instead of gets() because the compiler says that gets()function is "deprecated".but when I change sizeof(source) in the code to an integer value suppose 50 the code works fine. Can anybody tell me what wrong with this code and why on earth the compiler say that gets() function is deprecated.
This is the code:
#include <stdio.h>
#include <stdlib.h>
int len(char *source);
char *coppy(char *dest,char *source);
int main (void){
char *source,*dest;
source=(char *)malloc(len(source)+1);
printf("enter string:");
fgets(source,sizeof(source),stdin);
if(source[len(source)-1]=='\n'){
source[len(source)-1]='\0';
}
dest=(char *)malloc(len(source)+1);
coppy(dest,source);
printf("dest=%s\n",dest);
printf("length source=%d\n",len(source));
printf("length dest=%d\n",len(dest));
return 0;
}
int len(char *source){
int i=0;
while(*source!='\0'){
source++;
i++;
}
return i;
}
char *coppy(char *dest,char *source){
while(*source!='\0'){
*dest=*source;
source++;
dest++;
}
*dest='\0';
return dest;
}
This is the result when run that code:
enter string:programming
dest=pro
length source=3
length dest=3
Here is your first mistake:
source=(char *)malloc(len(source)+1)
You pass source to the function len before you initialized it, which is undefined behaviour. From hereon in, anything could happen.
The second mistake is your use of fgets:
fgets(source,sizeof(source),stdin);
The second argument to fgets is supposed to be how many characters are available to be written in, not sizeof(source). Read the documentation for fgets, and sizeof if necessary.
Your error is in how you allocate memory for source
source=(char *)malloc(len(source)+1);
What did you expect len(source) to be? Play computer and run through your len function. I'm surprised your code compiles and runs at all. Your len function on an uninitialized char* should be undefined behavior.
That is why your code fails, you are not allocating enough memory to hold your input string.