Hey, I've been trying to get this to work for most of the day. Basically I have an array of strings and I'm adding to them using strcat in a loop. It works fine for the first few loops but then the strings start to go all out of whack. I assumed it was something to do with not enough memory but no matter how much I allocate it gave the same result.
I got it working by using

char output[elements][100]

but i'd rather not do that.

char buf[10];
	char **output = malloc(elements*sizeof(char *));
	int i;
	for(i = 0; i <= elements; i++) {
		output[i] = malloc(1000*sizeof(char));
		output[i] = names[i];
	}

	while(finished < elements){
		printf(output[index]);
		printf("\n");
		if(start[index] <= time){
			if(left[index] >= quanta){
				sprintf(buf," (%d,%d)",time,quanta);
				strcat(output[index], buf);

				left[index] = left[index] - quanta;;
				if(left[index] <= 0){
					finished++;
				}
				time = time + quanta;
				index++;
                }
        ....
        ....

Any help is appreciated.

for(i = 0; i <= elements; i++) {

This is an off-by-one error. The last value element is output[elements-1] , not output[elements] .

output[i] = malloc(1000*sizeof(char));
output[i] = names[i];

So you allocate memory, then immediately throw away your only reference to the memory just allocated? That's called a memory leak.

Since you got it to work using an array, that means your allocation logic is likely wrong. To match the declaration of char output[elements][100] , you'd do this (error checking omitted for brevity):

char **output = malloc(elements * sizeof *output);

for (i = 0; i < elements; i++) {
    output[i] = malloc(100);
    output[i][0] = '\0' /* Make it a valid string for strcat() */
}

And the cleanup would look like this:

for (i = 0; i < elements;i++)
    free(output[i]);

free(output);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.