Having trouble figuring out why I run into a segmentation fault with the longer piece of code.
I take this and run it fine.
struct Earthquake
{
char *prevString;
char *magString;
char *postString;
};
int main(void)
{
struct Earthquake eq;
eq.prevString="PREVIOUS STRING";
eq.magString = "50";
eq.postString = "POST STRING";
printf("\n%s",eq.prevString);
printf("\n%s",eq.magString);
printf("\n%s\n",eq.postString);
}
When I try to run this I get a segmentation fault, which I stop getting if I comment out the struct initialization. You might be able to tell with what I have commented out, but once I get this working I'm trying to make a struct array at which point I know the eq needs to be an Earthquake pointer but I can't even get this working.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#include <stddef.h>
//#include <paths.h>
struct Earthquake
{
char *prevString;
char *magString;
char *postString;
};
int main()
{
int numLines = 0;
FILE *fileA = fopen("./all_month.csv", "r");
char c[1];
do
{
*c = fgetc(fileA);
//printf("%c", c);
}while(*c != '\n');
do
{
*c = fgetc(fileA);
//printf("%c", c);
if(*c == '\n')
{
numLines++;
}
}while(*c != EOF);
//printf("%d",numLines);
fclose(fileA);
FILE *fileB = fopen("./all_month.csv", "r");
char prevStringTemp[60];
char postStringTemp[150];
char magStringTemp[10];
struct Earthquake eq;
//if(NULL == (entries = (Earthquake *)malloc(sizeof(Earthquake) * numLines)));
//printf("\nmalloc failed\n");
do
{
*c = fgetc(fileB);
//printf("%c", c);
}while(*c != '\n');
char line[200];
int commaCount = 0;
do{
*c = fgetc(fileB);
if(*c==',')
{
commaCount++;
//printf("\n%d", commaCount);
}
strcat(prevStringTemp, c);
}while(commaCount<4);
do
{
*c = fgetc(fileB);
strcat(magStringTemp, c);
}while(*c!=',');
do
{
*c = fgetc(fileB);
strcat(postStringTemp, c);
}while(*c!='\n');
//strcpy(entries[0].prevString, prevString);
//printf(entries[0].prevString);
//fscanf(fileB,"%s",line);
//printf("\n%s\n", line);
fclose(fileB);
//free(entries);
return 0;
}
This is the problem
strcat(prevStringTemp, c);
beacause strcat() expects nul terminated strings which niether the parameters is in your case.
Your c array should be
char c[2] = {0};
and the first element of these
char prevStringTemp[60];
char postStringTemp[150];
char magStringTemp[10];
should be initialized to '\0', like this
prevStringTemp[0] = '\0';
postStringTemp[0] = '\0';
magStringTemp[0] = '\0';
after fixing this, strcat() will behave as you expect.
Related
#include <string.h>
#include <stdio.h>
int main()
{
char str[255] = "Hello;thisnewwolrd";
int i =0;
while(str[i] != ';')
{
i++;
}
i++;
char *name = NULL;
while(str[i] != NULL)
{
name[i] = str[i];
i++;
printf("%c \r\n",name[i]);
}
}
the expected output is thisnewwolrd but i am getting error of core dumped
canany one have reason why and how to over come this
This should work:
int main()
{
char str[255] = "Hello;thisnewwolrd";
char *ptr = strchr(str, ';') + 1;
char name[255];
strcpy( name, ptr);
printf("%s \r\n", name);
}
You don't have to reinvent the wheel, and are much better off using standard library functions for string manipulation.
You have to allocate memory to store your string copy. For example: char *name = malloc(255*sizeof(char));.
And you have to create another iterator than i to start to fill the memory space pointed by name starting at the index 0.
Here two prgrams present. Program 1 and program 2.
Input to both programs: {(0,0),(25,25)}
Output is : (0,0),(25,25)
The program -1 is working fine, giving out put as expected. Program 2 is not giving out put as expected bot no errors.
Suspecting problem at *str2 = *token in program -2.But what the problem is not identified exactly. can any one explain me
Program --1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
char* fun_call(char [], int );
int main()
{
char str[] = "{(0,0),(25,25)}";
int base_str_leng;
char *retun_ptr;
base_str_leng = sizeof(str)-1;
printf("base_str_lemg:%d\n",base_str_leng);
retun_ptr = fun_call(str, base_str_leng);
printf("str2 in main loop:::%s\n",retun_ptr);
return 0;
}
char* fun_call(char str1[], int len)
{
printf("len::%d\n", len);
len = len-2;
printf("len=%d\n",len);
char *token = str1;
char *str2 = (char*) malloc( len * sizeof(char) );
printf("sizeof(str2) = %zd\n",malloc_usable_size(str2));
printf("token:%s\n", token);
printf("****While loop started****\n");
int i=0,j=0;
while(token[i] != '\0')
{
if(token[i] != '{' && token[i] != '}' )
{
printf("Each token:%c\n", token[i]);
str2[j] = token[i];
i++;
j++;
printf("str2_Token::%c\n", str2[j]);
}
else
{
i++;
}
}
printf("Function str2::%s\n", str2);
return (str2);
}
Program: 2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
char* fun_call(char [], int );
int main()
{
char str[] = "{(0,0),(25,25)}";
int base_str_leng;
char *retun_ptr;
base_str_leng = sizeof(str)-1;
printf("base_str_lemg:%d\n",base_str_leng);
retun_ptr = fun_call(str, base_str_leng);
printf("str2 in main loop:::%s\n",retun_ptr);
return 0;
}
char* fun_call(char str1[], int len)
{
printf("len::%d\n", len);
len = len-2;
printf("len=%d\n",len);
char *token = str1;
char *str2 = (char*) malloc( len * sizeof(char) );
printf("sizeof(str2) = %zd\n",malloc_usable_size(str2));
printf("token:%s\n", token);
printf("****While loop started****\n");
while(*token != '\0')
{
if(*token != '{' && *token != '}' )
{
// printf("Each token:%c\n", token[i]);
*str2 = *token;
str2++;
token++;
// printf("str2_Token::%c\n",*str2);
}
else
{
token++;
}
}
printf("Function str2::%s\n", str2);
return (str2);
}
In your program 2 you do not end the string with \0, your while loop ends when token[i] == '\0'
You could use calloc instead to initialize the memory to 0
char *str2 = calloc( len, sizeof(char) );
I am writing a function in C to get the next word from a string (*s) and copy it into the buffer (*w). It returns the first char of the word.
It works fine when the input string is a char pointer (char *text), but when I change the type to a char array (char [MAXTEXT]) the program crashes.
This is confusing me, as I thought the compiler 'decayed' char arrays into char pointers anyway. To my belief, whether the input is a char pointer or a char array shouldn't make a difference?
(The declaration is at line 10 char *text = "This should return the first word";, which crashes when changed to char text[MAXTEXT] = "This should return the first word";)
#include <stdio.h>
#include <ctype.h>
#define MAXTEXT 1000
int getword(char *inp, char *out, int lim);
void main()
{
char *text = "This should return the first word";
char *word;
int i, c;
printf("%c", getword(text, word, MAXTEXT));
printf("%s", word);
}
int getword(char *s, char *w, int lim)
{
static int bufp = 0;
char c;
char *word = w;
while (isspace(c = s[bufp++]));
if (c != EOF)
*w++ = c;
else if (!isalpha(c))
{
*w = '\0';
return c;
};
for (; --lim > 0; bufp++)
if (isalpha(c = s[bufp]) || c == '\'')
*w++ = s[bufp];
else
break;
*w = '\0';
return word[0];
}
The problem is that for the pointer word, you haven't allocated any memory. Simply allocating memory will fix the problem.
Your array implementation:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define MAXTEXT 1000
char getword(char *inp, char *out, int lim);
int main()
{
char text[100],word[100];
// char *text = (char*)calloc(100,sizeof(char));
strcpy(text,"This should return the first word");
// char *word = (char*)calloc(100,sizeof(char));
int i, c;
printf("%c", getword(text, word, MAXTEXT));
// printf("%s", text);
return 0;
}
char getword(char *s, char *w, int lim)
{
static int bufp = 0;
char c;
char *word = w;
while (isspace(c = s[bufp++]));
if (c != EOF)
*w++ = c;
else if (!isalpha(c))
{
*w = '\0';
return c;
};
for (; --lim > 0; bufp++)
if (isalpha(c = s[bufp]) || c == '\'')
*w++ = s[bufp];
else
break;
*w = '\0';
return word[0];
}
Hi I am trying to right a program but am having so much difficulty. The program is a challenge I made up myself. I want to read in 6 strings from the user. Then I want to create a function that will allow me to compare those strings to find which string is different in size. Then I want to pass this info to another function that will determine the string length of the string that is different. Finally print the value. Here is what I have done thus far (many many errors).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* diffFun(char* ,char*,char * ,char *,char * ,char *)
{
char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
char *s6;
char *result;
if (strcmp(s2,s3,s4,s5,s6)<strcmp(s1))
result = s1;
else if (strcmp(s1,s3,s4,s5,s6)<strcmp(s2))
result s2;
return result;
}
int main()
{
char *str1;
char *str2;
char *str3;
char *str4;
char *str5;
char *str6;
printf("Give me a string1:\n");
str1 = readString(stdin);
printf("Give me a string2:\n");
str2 = readString(stdin);
printf("Give me a string3:\n");
str3 = readString(stdin);
printf("Give me a string4:\n");
str4 = readString(stdin);
printf("Give me a string5:\n");
str5 = readString(stdin);
printf("Give me a string6:\n");
str6 = readString(stdin);
char *cond;
cond = diffFun((char* str1,char* str2,char* str3,char* str4,char* str5,char* str6);
printf("%ls",cond);
return 0;
}
I do not understand well, but I feel like the following...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* diffFun(int n, char *s[n]){
int i, j;
char *result = s[0];
size_t result_len = strlen(result);
for(i = 1; i < n; ++i){
size_t len = strlen(s[i]);
if(result_len < len){
result = s[i];
result_len = len;
} else if(result_len == len && strcmp(result, s[i]) < 0){
result = s[i];
}
}
return result;
}
int main(void){
char *str[6];
int i;
for(i=0;i<6; i++){
printf("Give me a string%d:\n", i+1);
str[i] = readString(stdin);
}
char *cond = diffFun(6, str);
printf("%s",cond);
return 0;
}
This is my code:
#include <stdio.h>
#include <stdlib.h>
void getinfo(unsigned int a, unsigned int b, char **s);
int main(){
unsigned int len_max = 8;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
if(pStr == NULL){
perror("\nMemory allocation\n");
return EXIT_FAILURE;
}
current_size = len_max;
printf("Inserisci hostname: ");
getinfo(len_max, current_size, &pStr);
printf("\nLa stringa inserita รจ: %s\n", pStr);
free(pStr);
return EXIT_SUCCESS;
}
void getinfo(unsigned int a, unsigned int b, char **pStr){
unsigned int i = 0;
char c = EOF;
while((c = getchar()) != '\n'){
*pStr[i++] = (char)c;
if(i == b){
b = i+a;
if((*pStr = realloc(*pStr, b)) == NULL){
perror("\nMemory allocation error\n");
exit(EXIT_FAILURE);
}
}
}
*pStr[i]='\0';
}
When i execute this code i got a segmentation fault when i press enter (after i've wrote the string).
I'm sure the problem is into the function (probably the problem is the *s pointer) but i don't know how to correct it...
You have a precedence problem. You need to use
(*s)[i++] = ...
instead of
*s[i++] = ...
Similarly you need
(*s)[i]='\0';
When you write *s[i] you are indexing s. But you want to index *s, and hence require the parentheses.
I've not checked the rest of your code, but I hope this helps you on your way to debugging the rest of it, if indeed there are more errors.
The problem is with *s[i++] = (char)c; try turning it into (*s)[i++] = (char)c; with the parenthesis around the *s. As well as (*s)[i] = '\0'.