Combining Strings - Segmentation Fault


 
Thread Tools Search this Thread
Top Forums Programming Combining Strings - Segmentation Fault
# 8  
Old 02-11-2007
Your original segfault is as milhan pointed out - you didn't initialise count1, so when you reference string1[count1] you are doing the same thing as string1[some_garbage_value].

Fix that and you still end up with a segfault. Why? You need to declare your function as returning a pointer (as Perderabo mentioned).

Try this:

Code:
char *combine(char string1[MAXINPUT], char string2[MAXINPUT])

As it stands, your program is like a bomb waiting to explode. This...

Code:
scanf("%s", string1);

...is just as bad as using gets to get the input into the string. I understand that this is a toy program you are learning from, but why not learn to do things correctly from the beginning? What happens when the user decides to enter more characters than MAXINPUT? The end of the array will happily be overwritten, and you will have corrupted memory. Consult your manual for fgets, and start using it.

Also, when you do this...

Code:
if ((sizeof string1) > MAXINPUT) {

...what do you think the result of the sizeof is? Consider the following:

Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char array1[10];
    char array2[20];
    char *p;

    printf("\n\nEnter some text for array1: ");
    fflush(stdout);
    if ((fgets(array1, sizeof(array1), stdin)) == NULL) {
        fprintf(stderr, "%s\n", "fgets error!");
        exit(EXIT_FAILURE);
    }

    if ((p = strchr(array1, '\n')) != NULL) {
        *p = '\0';
    }

    printf("The string you entered for array1: '%s'\n", array1);
    printf("sizeof(array1): %zu\n", sizeof(array1));
    printf("strlen(array1): %zu\n", strlen(array1));

    printf("\n\nEnter some text for array2: ");
    fflush(stdout);
    if ((fgets(array2, sizeof(array2), stdin)) == NULL) {
        fprintf(stderr, "%s\n", "fgets error!");
        exit(EXIT_FAILURE);
    }

    if ((p = strchr(array2, '\n')) != NULL) {
        *p = '\0';
    }

    printf("The string you entered for array2: '%s'\n", array2);
    printf("sizeof(array2): %zu\n", sizeof(array2));
    printf("strlen(array2): %zu\n", strlen(array2));

    return 0;
}

/* My results:

 $ gcc -Wall -o example example.c
 $ ./example


Enter some text for array1: hello
The string you entered for array1: 'hello'
sizeof(array1): 10
strlen(array1): 5


Enter some text for array2: nananannananna
The string you entered for array2: 'nananannananna'
sizeof(array2): 20
strlen(array2): 14
 $     

*/

Study that, and I think you will see the problem. When you are done, read this. It is an interesting article about getting rid of macros to define array sizes.

Last edited by kermit; 02-11-2007 at 10:57 AM..
# 9  
Old 02-11-2007
that was a good catch. I missed that twice.. the combine function is just returning a copy of the first character from string1, so it has to be declared as returning char * to the first character of the new string array...

This fixes the segmantation fault error. But there is another "logical" error.

when you pass the original string1 and string2 strings (char arrays) to combine function; the combine function actually modifies the string1 passed to it from main(). This has nothing to do with having the same var name. (Even if i changed the var names, it still does the same thing). anyone know why this is happening?

combine func() is declared like this:
Code:
char *combine(char str1[MAX], char str2[MAX]) { ... }

is this not supposed to create new local str[] and str2[] as opposed to actually pointing to the actual var's passed..?
# 10  
Old 02-11-2007
When you pass an array name to a function, it decays to a pointer to the first element of the array.
# 11  
Old 02-11-2007
milhan/kermit, I just updated my code, and still prduces a segmentation fault, I must have not read correctly/understood kermit's post:
Code:
#include <stdio.h>
/* #include <string.h> == cheating! */

char combine(char string1[1000], char string2[1000]) {
	int count1 = 0, count2 = 0;

	while (string1[count1] != '\0')
		++count1;
	while (string2[count2] != '\0')
		string1[count1++] = string2[count2++];
	string1[count1] = '\0';

	return string1[0];
}

main() {
	char string1[1000];
	char string2[1000];
	int i = 0;
	int count = 0;
	
	printf("Enter two strings each under 1000 characters:\n");
	while(i == 0) {
		printf("1: ");
		scanf("%s", string1);
		while (string1[count] != '\0')
			++count;
		if (count > 1000) {
			i = 0;
			printf("I said under 1000 characters, please enter it again:\n");
		}
		else
			i = 1;
	}
	count = i = 0;
	while(i == 0) {
		printf("2: ");
		scanf("%s", string2);
		while (string2[count] != '\0')
			++count;
		if (count > 1000) {
			i = 0;
			printf("I said under 1000 characters, please enter it again:\n");
		}
		else
			i = 1;
	}
	printf("%s and %s combined is %s", string1, string2, combine(string1, string2));
	return 0;
}

in main(), i added count to count the characters in string1, and string2. I choose not to use strlen() that is declared in string.h, because that is "cheating", or so I am calling it for this.

I read the article, and fixed all the MAXLINE, as you can see. I got the MAXLINE, from a the book, "The C Programing Language (ansi C)", also refered to as K&R, because of the authors. Why does sizeof() produce a larger value then strlen()? Is sizeof() just byte size?

Kermit, I had also realized that this isn't great code from when I started writing it.

thanks, for reading.
# 12  
Old 02-12-2007
If you are not reading replies to your post how can you expect problem to be fixed? Perderabo and Kermit both have mentioned that problem is with the return type, it should be char pointer, try this at function declaration and post the result:
Code:
char *combine(char string1[1000], char string2[1000])

And while returning no need to mention array subscript, since return type is pointer, modify your return statement like this:
Code:
return string1;


Last edited by tayyabq8; 02-12-2007 at 01:16 AM..
# 13  
Old 02-12-2007
Quote:
Originally Posted by tayyabq8
If you are not reading replies to your post how can you expect problem to be fixed? Perderabo and Kermit both have mentioned that problem is with the return type, it should be char pointer, try this at function declaration and post the result:
Code:
char *combine(char string1[1000], char string2[1000])

And while returning no need to mention array subscript, since return type is pointer, modify your return statement like this:
Code:
return string1;

Thanks. I haven't learned that much on pointers yet.

It works fine, but I had a logical erorr. At the end it returns string1 and string2, and string1 is string1 and string2 combined. I should have it fixed soon.
# 14  
Old 02-12-2007
Quote:
Originally Posted by Octal
It works fine, but I had a logical erorr. At the end it returns string1 and string2, and string1 is string1 and string2 combined. I should have it fixed soon.
that's what I warned about at my last post above. in order to get around that, just copy the strings inside the combine function to temporary ones, so that the original ones won't be messed up. (i'm sure you know how to do that: just make two while loops that copies the char []'s ..)
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Programming

C. To segmentation fault or not to segmentation fault, that is the question.

Oddities with gcc, 2.95.3 for the AMIGA and 4.2.1 for MY current OSX 10.14.1... I am creating a basic calculator for the AMIGA ADE *NIX emulator in C as it does not have one. Below are two very condensed snippets of which I have added the results inside the each code section. IMPORTANT!... (11 Replies)
Discussion started by: wisecracker
11 Replies

2. Homework & Coursework Questions

Segmentation Fault

this is a network programming code to run a rock paper scissors in a client and server. I completed it and it was working without any error. After I added the findWinner function to the server code it starts giving me segmentation fault. -the segmentation fault is fixed Current problem -Also... (3 Replies)
Discussion started by: femchi
3 Replies

3. Programming

Using gdb, ignore beginning segmentation fault until reproduce environment segmentation fault

I use a binary name (ie polo) it gets some parameter , so for debugging normally i do this : i wrote script for watchdog my app (polo) and check every second if it's not running then start it , the problem is , if my app , remain in state of segmentation fault for a while (ie 15 ... (6 Replies)
Discussion started by: pooyair
6 Replies

4. UNIX for Advanced & Expert Users

segmentation fault with ps

What does this mean and why is this happening? $ ps -ef | grep ocular Segmentation fault (core dumped) $ ps -ef | grep ocular Segmentation fault (core dumped) $ ps aux | grep ocular Segmentation fault (core dumped) $ ps Segmentation fault (core dumped) $ pkill okular $ ps... (1 Reply)
Discussion started by: cokedude
1 Replies

5. Programming

segmentation fault.

This code is causing a segmentation fault and I can't figure out why. I'm new to UNIX and I need to learn how to avoid this segmentation fault thing. Thank you so much. Thanks also for the great answers to my last post.:):b: int main() { mysqlpp::Connection conn(false); if... (3 Replies)
Discussion started by: sepoto
3 Replies

6. Programming

Segmentation fault.

I'm getting a segmentation fault. I'm new to Linux programming. Thanks so much for all of your input.:eek: #include </usr/include/mysql++/mysql++.h> #include <stdio.h> #include <iostream> #include <sstream> #include <string.h> using namespace std; int outputToImport(const char*... (1 Reply)
Discussion started by: sepoto
1 Replies

7. Programming

segmentation fault

What is segmentation fault(core dumped) (1 Reply)
Discussion started by: gokult
1 Replies

8. Programming

segmentation fault

If I do this. Assume struct life { char *nolife; } struct life **life; // malloc initialization & everything if(life->nolife == 0) Would I get error at life->nolife if it is equal to 0. wrong accession? (3 Replies)
Discussion started by: joey
3 Replies

9. Programming

Why not a segmentation fault??

Hi, Why I don't receive a segmentation fault in the following sample. int main(void) { char buff; sprintf(buff,"Hello world"); printf("%s\n",buff); } If I define a buffer of 10 elements and I'm trying to put inside it twelve elements, Should I receive a sigsev... (22 Replies)
Discussion started by: lagigliaivan
22 Replies
Login or Register to Ask a Question