So I'm working on a program where the function reads in from stdio, and keeps reading in characters in chunks of n characters.
So far I've gotten it so that everything is stored in a character array called buffer. For the next step, I need to sort each chunk of n characters. For example the string cats/ndogs/n should be split as cats/n dogs/n if n =5, and then qsort() needs to alphabetize it. This is how I'm calling qsort():
qsort (buffer, (line-2)*n*(sizeof(char)),n,compare);
Where (line-2)*n*sizeof(char) gives the total number of items in the array buffer; 10 in this case.
This is my compare function:
int compare (const void * a, const void * b)
{
return (strcmp(*(char **)a, *(char **)b));
}
When I run this, however, I always get a seg fault in strcmp(). Any ideas why?
This is the loading code:
while (!feof(stdin))
{
for (i = 0; i < n; i++)
{
char l = getchar();
if (l != EOF)
{
if ((i == 0) && (line != 1))
{
success = (int *)realloc(buffer, line*n*(sizeof(char)));
}
buffer[(n*(line-1))+i] = l;
}
}
line = line + 1;
}
Silly question, but are your strings null terminated? You seem to only have a newline on the end.
Also, you probably only need "strcmp((char *)a, (char *)b)" as the extra *s look to be redundant to me.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char buffer[] ="333000222555111777888666999444";
int mycmp(void *l, void*r);
int main(void)
{
/* note: sizeof buffer is 31,
** but the integer division will round down
** , ignoring the extra nul-byte */
qsort(buffer, (sizeof buffer/3), 3, mycmp);
printf ("[%s]\n", buffer);
return 0;
}
int mycmp(void *l, void *r)
{
return memcmp(l,r,3);
}
Related
I tried to run a C program that reads from stdin and stores them in char**, but I keep getting either malloc: Incorrect checksum for freed object or segmentation fault errors whenever realloc is used to increase the size of the pointer. Can anyone point out what I did wrong? The program is example 7_14 from beginning C 5th ed. Below is the code I ran without using C11 optional string functions because my clang complier doesn't seem to support them.
// Program 7.14 Using array notation with pointers to sort strings
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define BUF_LEN 100
#define COUNT 5
int main(void)
{
char buf[BUF_LEN]; // Input buffer
size_t str_count = 0; // Current string count
size_t capacity = COUNT; // Current maximum number of strings
char **pS = calloc(capacity, sizeof(char *)); // Pointers to strings
char **psTemp = NULL; // Temporary pointer to pointer to char
char *pTemp = NULL; // Temporary pointer to char
size_t str_len = 0; // Length of a string
bool sorted = false; // Indicated when strings are sorted
printf("Enter strings to be sorted, one per line. Press Enter to end:\n");
// Read in all the strings
char *ptr = NULL;
while (*fgets(buf, BUF_LEN, stdin) != '\n')
{
if(str_count == capacity)
{
capacity += capacity/4;
if (!(psTemp = realloc(pS, capacity))) return 1;
pS = psTemp;
}
str_len = strnlen(buf, BUF_LEN) + 1;
if (!(pS[str_count] = malloc(str_len))) return 2;
strcpy(pS[str_count++], buf);
}
// Sort the strings in ascending order
while(!sorted)
{
sorted = true;
for(size_t i = 0; i < str_count - 1; ++i)
{
if(strcmp(pS[i], pS[i + 1]) > 0)
{
sorted = false;
pTemp = pS[i];
pS[i] = pS[i+1];
pS[i+1] = pTemp;
}
}
}
// Output the sorted strings
printf("Your input sorted in ascending sequence is:\n\n");
for(size_t i = 0; i < str_count; ++i)
{
printf("%s", pS[i]);
free(pS[i]);
pS[i] = NULL;
}
free(pS);
pS = NULL;
return 0;
}
Example execution result:
Enter strings to be sorted, one per line. Press Enter to end:
Many a mickle makes a muckle.
A fool and your money are soon partners.
Every dog has his day.
Do unto others before they do it to you.
A nod is as good as a wink to a blind horse.
The bigger they are, the harder they hit.
[1] 82729 segmentation fault ./7_14
This question already has answers here:
What is going on with 'gets(stdin)' on the site coderbyte?
(3 answers)
Closed 3 years ago.
I am trying to do the following coding challenge in C:
Challenge:
Using the C language, have the function AlphabetSoup(str) take the str string parameter being passed and return the string with the letters in alphabetical order (ie. hello becomes ehllo). Assume numbers and punctuation symbols will not be included in the string.
Attempt:
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void* val_1, const void* val_2){
return (*(char *)val_1 - *(char *)val_2);
}
int str_size(char* str[]){
int size = 0;
while(str[size] != '\0')
size++;
return size;
}
void AlphabetSoup(char * str[]) {
qsort(str,str_size(str), sizeof(char), cmpfunc);
printf("%s", str);
}
int main(void) {
// disable stdout buffering
setvbuf(stdout, NULL, _IONBF, 0);
// keep this function call here
AlphabetSoup(gets(stdin));
return 0;
}
I am not getting any output for this code. I think the problem is the cmpfunc function. I am not implementing it correctly. I neither understand how it works inside qsort. My understanding is that val_1 and val_2 are pointers to two chunks of memory in the array and somehow I have to cast these chunks to the right type.
I am also getting a non-zero status for the following code:
void AlphabetSoup(char * str[]) {
int str_size_ = str_size(str);
int int_rpr[str_size_];
int i;
for(i = 0; i < str_size; i++){
int_rpr[i] = (int)str[i];
}
printf("%i", str_size_);
//printf("%s", str);
//qsort(int_rpr,str_size_, sizeof(int), cmpfunc);
//for(i = 0; i < str_size; i++){
// printf("%c", str[i]);
// }
}
when I get rid of int_rpr[i] = (int)str[i];and replace it by any random statement like int b; b = 0; , it works.
coding challenge link: https://coderbyte.com/editor/Alphabet%20Soup:C
It was asked you parse an argument (not a string from stdin), so you need to use argc and argv. Also sizeof(char) is 1 by the C standard, so is superfluous.
Don't duplicate strlen either, we have libraries for a reason.
I'd do it this way (which I confirmed works on my system)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int char_cmp(const void *pa, const void *pb){
char a = *((char *) pa), b= *((char *) pb);
if (a < b){
return -1;
} else if (a > b){
return 1;
} else {
return 0;
}
}
int main(int argc, char *argv[]){
char *input= NULL;
if (2 != argc){
fprintf(stdout, "give one argument string\n");
return 1;
} else {
input = strdup(argv[1]);
if (NULL == input){
fprintf(stderr, "memory error\n");
return 2;
}
}
qsort(input, strlen(input), 1, char_cmp);
fprintf(stdout, "%s\n", input);
free(input);
return 0;
}
I have created a function for strend, which basically returns 1 if string t is present at the end of string s, however it never returns 1:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int strend(char *s, char *t) {
int p;
for (p = 0; p < strlen(s) - strlen(t); p++) {
*s++;
}
printf("%s\n%s\n", s, t);
if (s == t)
return 1;
return 0;
}
int main(void) {
int bool = strend("Hello", "ello");
printf("%i\n", bool);
return 0;
}
This gives me an output of:
ello
ello
0
So technically I should get 1. I assume the comparison using pointers is not used in this way?
You need to review your basic knowledge of C strings. There are lots of standard string functions in string.h that can help you with this test.
The basic problem is that the test s == t is valid, but you are comparing memory addresses here. You can see that is valid if you change the strings to test to
char test[] = "Hello";
int bool = strend_(test, test+1);
where test obviously is the same as your "Hello", and similarly, test+1 is the same as "ello" (try it by printing them). This correctly returns 1 with your routine.
In addition, I get two warnings:
on *s++; "warning: expression result unused [-Wunused-value]": you increment s but also ask what character is at that position through *s; and you don't use that information.
Fix by removing the * there.
on p < strlen(s) ..; "warning: comparison of integers of different signs: 'int' and 'unsigned long'", because strlen does not return a signed integer but an unsigned one (apparently, my header uses unsigned long).
Fix by declaring p as unsigned long, or even better, size_t.
Your entire routine can be condensed to a simple
int strend (char *s, char *t)
{
if (strlen(s) >= strlen(t) && !strcmp (s+strlen(s)-strlen(t),t))
return 1;
return 0;
}
It's not worth the trouble to cache the result of those four strlen calls into 2 temporary variables; a good compiler will work it out and do that for you. (A quick glance to the assembly output of the compiler I'm using – clang – shows it does, even with the default optimization settings.)
A slightly modified test, based on #M.M.'s comment:
int strend (char *s, char *t)
{
if (strlen(s) < strlen(t)) return 0;
return !strcmp (s+strlen(s)-strlen(t),t);
}
but attempting to optimize it this way is not as easy parsed as the routine above, and its assembly is ever so slightly "wordy" as well. Personally, I'd go for the more humanly readable version.
Use strcmp(3)
if (strcmp(s, t) == 0) return 1;
This actually compares the contents of the memory pointed to by s and t rather than their addresses.
Your code is broken in multiple ways:
The initial loop is a very cumbersome way to advance p by the difference of lengths if positive.
Once you have pointers at the same distance from the end of both strings, You should compare the characters with strcmp() (or memcmp() if you can first exclude the case of strlen(s) < strlen(t).
Comparing the pointers obtained after the loop will only work if t points inside the string pointed to by s, a special case that may or may not be produced by the compiler for the specific call in main: strend("Hello", "ello");.
Here is a modified version:
#include <string.h>
int strend(const char *str1, const char *str2) {
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
return len1 >= len2 && !memcmp(str1 + len1 - len2, str2, len2);
}
I corrected/modified your code, here is the code,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#pragma warning(disable:4996)
int strend(char *s, char *t)
{
int p,flag=0,count=0;//count will be the starting index for *t
p = strlen(s) - strlen(t);//this will be the starting index for *s
while(count<strlen(t))
{
if (*(s+p) == *(t+count))
{
flag = 1;
count++;
p++;
continue;
}
else
{
flag = 0;
break;
}
}
return flag;
}
int main(void)
{
int flag = strend("Hello", "ello");
printf("%i\n", flag);
return 0;
}
This code works too.
#include <stdio.h>
#include <string.h>
int strend (char *s1, char *s2);
void main ()
{
char str1[20] = "somethings";
char str2[20] = "things";
int f;
f = strend (str1,str2);
if (f==1)
printf ("1");
else
printf ("0");
}
int strend (char *str1, char *str2)
{
int l = strlen(str1) - strlen(str2);
str1 = str1 + l;
int d = strcmp(str1,str2);
if (d == 0)
return 1;
else
return 0;
}
this code works well.
int strend(char *s, char *t){
while(*t & *s){
if(*t == *s){
t++;
}
s++;
}
return *t==*s;
}
I need to write a probram in C, which adds a string to a string etc. (for example '5' strings - It needs to read "vbvbvbvbvb" 5 times.) But it doesn't work? Help please!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[80];
int len;
int counter = 0;
char* repeat(char* s, int n) {
if (n > 0) {
if (s[len] == n) {
counter++;
}
len--;
repeat(s, (n++));
}
return s;
}
int main(void) {
printf("%s", repeat("vb", 5));
fflush(stdout);
return EXIT_SUCCESS;
}
You're trying to write into the end of "vb" which is a string in the constant pool. Don't do that. Allocate a string that is strlen(s) * n + 1 long and write into that.
Your base case is probably wrong. The base case should probably be when n == 0 which is when the empty string (nothing appended except terminating NUL as below) is appropriate.
Your recursive step (n++) should probably be (n - 1) to count down to that base case. As written, the post-increment does a useless assign and recurses with the same value of n.
I don't know what counter and len are supposed to do, but they looks redundant to me. len is uninitialized, so s[len] has undefined behavior.
After writing the n copies, you need to add a terminating NUL ('\0') at the end so that printf and similar functions can identify the end.
You are using s both as a global and a local variable, the function is working on the local.
Try not to use global variables where not necessary. Also, recursion is not necessary for this.
#include <stdio.h>
void concatenate_string(char *dest, const char *src, int n) {
char *s;
while(n--) {
s = (char*)src;
while(*(s))
*(dest++)=*(s++);
}
*(dest++) = 0;
}
int main(void) {
char out[80];
concatenate_string(out, "ab", 5);
printf("%s", out);
return 0;
}
I am trying to solve StringMerge (PP0504B) problem from SPOJ (PL). Basically the problem is to write a function string_merge(char *a, char *b) that returns a pointer to an char array with string created from char arrays with subsequent chars chosen alternately (length of the array is the length of the shorter array provided as an argument).
The program I've created works well with test cases but it fails when I post it to SPOJ's judge. I'm posting my code here, as I believe it the problem is related to memory allocation (I'm still learning this part of C) - could you take a look at my code?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define T_SIZE 1001
char* string_merge(char *a, char *b);
char* string_merge(char *a, char *b) {
int alen = strlen(a); int blen = strlen(b);
int len = (alen <= blen) ? alen : blen;
int i,j;
char *new_array = malloc (sizeof (char) * (len));
new_array[len] = '\0';
for(j=0,i=0;i<len;i++) {
new_array[j++] = a[i];
new_array[j++] = b[i];
}
return new_array;
}
int main() {
int n,c; scanf("%d", &n);
char word_a[T_SIZE];
char word_b[T_SIZE];
while(n--) {
scanf("%s %s", word_a, word_b);
char *x = string_merge(word_a, word_b);
printf("%s",x);
printf("\n");
memset(word_a, 0, T_SIZE);
memset(word_b, 0, T_SIZE);
memset(x,0,T_SIZE);
}
return 0;
}
Note: I'm compiling it with -std=c99 flag.
Off-by-one.
char *new_array = malloc (sizeof (char) * (len));
new_array[len] = '\0';
You're writing past the bounds of new_array. You must allocate space for len + 1 bytes:
char *new_array = malloc(len + 1);
Also, sizeof(char) is always 1, so spelling it out is superfluous, so are the parenthesis around len.
Woot, further errors!
So then you keep going and increment j twice within each iteration of the for loop. So essentially you end up writing (approximately) twice as many characters as you allocated space for.
Also, you're leaking memory by not free()ing the return value of string_merge() after use.
Furthermore, I don't see what the memsets are for, also I suggest you use fgets() and strtok_r() for getting the two words instead of scanf() (which doesn't do what you think it does).
char *new_array = malloc (sizeof (char) * (len*2 + 1));
new_array[len*2] = '\0';