What's wrong in this code? - c

I was trying to mimic strtok functionality but getting segmentation fault. Please help me out here.
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char argv[])
{
int i=0;
char c[]="get the hell out of here";
char *p;
char *temp=(char *)malloc(100);
while(c[i]!='\0')
{
if(c[i]!=' ')
{
*temp=c[i];
temp++;
i++;
}
else
{
*temp='\0';
printf("printing tokenn");
puts(temp);
i++;
temp="";
}
}
return 0;
}

temp="";
This causes temp to point at unmodifiable memory, leading to a fault the next time you try to modify through it. You wanted to restore temp to the value you got from malloc (which you forgot to save).

Related

Functions and strings

im very new to programming, trying to learn C and cant figure out how to create/use a simple function.
Im trying to create a function called stringtest and then call it into the main and simply make the string strA print ABC.
void stringtest(char strA[20])
{
strA = "ABC";
}
int main()
{
char strA;
stringtest(strA[20]);
printf("This is strA", strA);
return 0;
}
You need to read up on pointers and the C syntax in general.
This is one way you could do it.
#include <stdio.h>
#include <string.h>
void stringtest(char *strA) {
strcpy(strA, "ABC");
}
int main(int argc, const char * argv[]) {
char strA[20];
stringtest(&strA[0]);
printf("This is strA -> %s \n", strA);
return 0;
}
Take care,
/Anders.
I don't think your code ran!!
There are a lot of bugs and errors in your code.
See the code given below to understand how to do this:
#include <stdio.h>
char strA[20];
void stringtest(){
strA[0]='A';
strA[1]='B';
strA[2]='C';
strA[3]='\0';
}
int main(){
stringtest();
printf("This is strA %s",strA);
}

Unexpected output of printf for a string in C

Case 1:
When I take string input, it successfully gives the output, writing this piece of code:
#include <stdio.h>
int main()
{
char *str;
scanf("%s",&str);
printf("%s",&str);
return 0;
}
Case 2:
On the other hand, it throws a Runtime Error for this snippet:
#include <stdio.h>
int main()
{
char *str;
scanf("%s",&str);
printf("%s",str);
return 0;
}
I found this thing peculiar, and want to know why it happens...
Thanks in advance.
None of those two cases are right.
Case 1 only worked because you got lucky, probably by giving a short string as input. Try something like "bfjabfabjkbfjkasjkvasjkvjksbkjafbskjbfakbsjfbjasbfjasbfkjabsjfkbaksbfjasbfkja" and you'll suffer a seg fault, most likely.
You should have a block of memory associated with str, either on the stack by declaring an array for it or on the heap malloc'ing memory for it.
And you shouldn't use the & operator.
So it would go like this:
#include <stdio.h>
int main()
{
char str[50]; // 50 is arbitrary
scanf("%s",str);
printf("%s",str);
return 0;
}
or like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* str = malloc(50); // 50 is arbitrary
scanf("%s",str);
printf("%s",str);
free(str);
return 0;
}

segmentation fault on regex function

If I had this code all inside just one function, I could get everything working fine, but now my problem is that I can't read the results of my regex. When I try printing the first result, I get a segmentation fault. Instead, I was expecting the first regex result to appear of "T/2/b".
Also, the word "Matches" appears on the screen right before the segmentation fault occurred.
Is there something I'm missing?
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
typedef struct{
char str[1000];
} regex;
long regexmatch(const char* str,const char* regexs,size_t nummatch,regex** reg){
regex_t r;regmatch_t match[nummatch];
if (regcomp(&r,regexs,REG_EXTENDED) != 0){return -1;}
if (regexec(&r,str,nummatch,match,0)!=0){regfree(&r);return -1;}
size_t i=0;
for (i=0;i<nummatch;i++){
if (match[i].rm_so > -1){
memset((**reg).str,0,1000);
memcpy((**reg).str,(char*)(str+match[i].rm_so),match[i].rm_eo-match[i].rm_so);
(*reg)++; //this is where I load the result into the struct and advance the pointer.
}
}
char *p=(**reg).str;
*p='\0';
regfree(&r);
return 0;
}
int main(){
char buf[1000];
memset(buf,0,1000);
regex* r=(regex*)buf;
if (regexmatch("T/2/b","([A-Z]+)/([0-9]+)/([a-z]+)",10,&r)==0){
printf("Matches\n");
printf("%s\n",r->str); //causes segmentation fault. Expecting a "T/2/b" to be displayed instead.
}
}

Array with int and char in C

I need to put 3 strings on an array[3][3].
I tried to do it with pointers, but I only receive a single character.
#include <stdio.h>
int array[3][3]
char thing[5] = "thing";
main()
{
thing = array[0][0];
printf("%s", array[0][0];
}
Try this. With due respect your code absolutely incorrect and need many changes. You need to update your programming skills too.
#include <stdio.h>
#include <string.h>
char array[3][6]={0};
char *thing = "this";
main()
{
strcpy(array[0],thing);
printf("%s\n", array[0]);
}

Struggling with strings. What is wrong with my function?

I am trying to write a small function to trim left spaces from a string, but I cannot get it right. In this version, I get the following error:
bus error: 10
Could anyone please explain to me what I am doing wrong? I am not looking so much for an alternative piece of code, but would like to understand the errors in my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void trim_string(char *);
int main(int argc, char *argv[]) {
char *temp = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char *string) {
char *string_trimmed = "";
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
strcpy(string, string_trimmed);
}
I have now found a workaround solution, shown below. But I am still not very clear about what I did wrong in the first place:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 100
void trim_string(char [MAX_LENGTH]);
int main(int argc, char *argv[]) {
char temp[MAX_LENGTH] = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char string[MAX_LENGTH]) {
char string_trimmed[MAX_LENGTH];
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
printf("c\n");
strcpy(string, string_trimmed);
}
Both string and string_trimmed point to string literals, here in main:
char *temp = " I struggle with strings in C.\n";
^
|
This is a string literal
temp points to a string literal and the standard says you are not allowed to modify them.
In the function trim_string you are modifying a them which is undefined behavior of which a bus error is one possible result, although anything can happen.
string_trimmed either needs to be an array like this:
char string_trimmed[n] ;
where n is the size of your input using strlen(string) would probably make sense or dynamically allocated via malloc which you would need to free at the end of your function. The same things goes for your input from main, this would work as a substitute:
char temp[] = " I struggle with strings in C.\n";
For completeness sake, the draft C99 standard section 6.4.5 String literals paragraph 6 says (emphasis mine):
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.

Resources