Segmentation Faults Using C-Style Strings and Functions

I have an assignment for my Programming class that is meant to provide an understanding of pointers, and c-style strings by the end of it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string.h>
using namespace std;
int main (int argc, char * const argv[]) {
	size_t len,size,blanks;
	size = 0;
	char *strArray[10];
	char *result;
	char line[] = "ls -l -a l wc -c >>   myfile";
	len = strlen(line);
	cout << "The length of the line is " << len << endl;

	// Tokenize string "line" using space as delimiter.  Stores information in char string array strArray
	char *hold;
	hold = strtok(line, " ");
	strArray[0]=hold;
	for (int i = 1;i<10; i++) {	
		hold = strtok(NULL, " ");
		strArray[i] = hold;
		printf("%s\n",strArray[i]);
	}

	// Tallies the size of each piece of strArray into variable 'size'
	for (int i = 0; i<10; i++) {
		size = size + strlen(strArray[0]);
	}
	cout << size << endl;

	// Calculates the number of spaces by subtracting the 'size'(has no spaces) from the 'len'(has spaces)
	blanks = len - size; 
	
	// Use new
	char *p1 = new char[size+1];
	result = p1;
	cout << "The result is " << result << endl;
	
	char *ls;
	ls = strArray[0];
	printf("\n%s",ls);
	
	char p2[100];
	
	for (int i = 0; i<10; i++) {
		strcat(p2, strArray[i]);
	}
	cout << hold << endl;
	
    return 0;
}


I keep running into problems with the above section of code. I am admittedly weak in my understanding of how pointers work, but I have looked up information on many of the subjects and cannot grasp what is wrong. It seems that I only get a segmentation fault whenever I try to access the an element of strArray[i] in any for loop.

If I haven't been clear enough about my problem, please ask and I'll try and be more clear.
I'd say class is providing a very valuable lesson in the use of pointers and C-style strings.

The words "Segmentation Fault" should be forever etched in your brain when you encounter them or any function defined in <cstring>.

Read the "BUGS" section of the strtok() man page.

Avoid using these functions. If you do use them, note that:

These functions modify their first argument.

These functions cannot be used on constant strings.

Topic archived. No new replies allowed.