Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Reverse Strings Problem

realloc string

  • Please log in to reply
10 replies to this topic

#1 Sindorius

Sindorius

    CC Lurker

  • Just Joined
  • Pip
  • 6 posts

Posted 17 March 2011 - 11:31 AM

Hello everyone. Having some difficulty figuring out how to write a program for my C course.
The program basically prompts the user for up to 100 strings and if an empty line occurs (Nothing is entered but they press enter) it interprets it as end of input. After they've entered the strings of text, the program will display the strings in reverse order, i.e., if you typed:
one
two
three
it would display:
three
two
one
BUT what's making it trouble for me is the rules we have to follow. Each string has to be stored in its own dynamically allocated buffer. And also we're assuming the input strings are no longer than 250 characters for simplicity sakes. Now dynamic allocation in C++ was pretty easy for me but working with malloc/calloc/realloc has been a slight hassle in C. I'm sure using them in conjunction with strlen/strcpy is probably the key to this but so far I'm not grasping how exactly how I'm going to store them in their own dynamic buffers and then be able to spit them out in reverse. Any help or advice would be greatly appreciated.
  • 0

#2 rocketboy9000

rocketboy9000

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 79 posts

Posted 17 March 2011 - 12:40 PM

Make an array of 100 char*s, and a 250 char buffer string. Then read each line into the buffer, and then, allocating only enough memory to hold that string, put it into the array.
  • 0

#3 gregwarner

gregwarner

    Obi Wan of Programming

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1586 posts
  • Location:Arkansas
  • Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 17 March 2011 - 12:48 PM

Don't use strcpy(). Use strncpy(). It copies up to n chars instead of just looking for a null character. Use the max size of your buffer for "n". If you're going with rocketboy's suggestion, "n" would be 250.

Using strncpy() instead of strcpy() helps to prevent runtime errors such as buffer overflows.
  • 0

#4 eafkuor

eafkuor

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 214 posts

Posted 17 March 2011 - 01:02 PM

#include <stdio.h>

#include <string.h>

#include <stdlib.h>



#define MAX_STRINGS 100

#define MAX_LENGTH 250



int main(){

	int i;

	char **strings=malloc(sizeof(char **)*MAX_STRINGS);

	char *temp=malloc(MAX_LENGTH);



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

		temp=fgets(temp, MAX_LENGTH, stdin);

		temp[strlen(temp)-1]='\0';//remove the newline at the end of the string



		if(!strlen(temp)){//exit if the line is empty

			break;

		} else { //else store it

			(*strings)=malloc(sizeof(char *)*(strlen(temp)+1));

			strcpy(*strings, temp);

			strings++;

		}

	}



	printf("\n");



	//print the lines in reverse order

	for(strings--;i>0;strings--, i--){

		printf("%s\n", *strings);

	}



	return 0;

}

Edited by eafkuor, 17 March 2011 - 02:26 PM.

  • 0

#5 gregwarner

gregwarner

    Obi Wan of Programming

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1586 posts
  • Location:Arkansas
  • Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 17 March 2011 - 01:29 PM

(*strings)=malloc(sizeof(char *)*(strlen(temp)+1));


You're going to get a seg fault the first time this statement executes, because strings hasn't been allocated yet. You need to first initialize your array of 100 values before you can start allocating any memory for the strings.

The way you've set up the storage part of your program is very bad. You shouldn't increment the strings pointer itself to allocate new strings. The strings variable should be allocated once at the beginning to an array of char*'s of size 100.
  • 0

#6 eafkuor

eafkuor

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 214 posts

Posted 17 March 2011 - 02:15 PM

You're going to get a seg fault the first time this statement executes

well, ehm, it works :)
  • 0

#7 rocketboy9000

rocketboy9000

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 79 posts

Posted 17 March 2011 - 02:20 PM

Just because it works doesn't mean it's right.
(Maybe I should put that in my sig.)
  • 0

#8 eafkuor

eafkuor

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 214 posts

Posted 17 March 2011 - 02:25 PM

I guess I just forgot this ?

strings=malloc(sizeof(char **)*MAX_STRINGS);

Edited by eafkuor, 17 March 2011 - 03:12 PM.

  • 0

#9 gregwarner

gregwarner

    Obi Wan of Programming

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1586 posts
  • Location:Arkansas
  • Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 17 March 2011 - 08:16 PM

well, ehm, it works :)


Sorry, edit. Saw that you posted before me.

Yes, you need something like that before you can allocate memory for the actual strings themselves.
  • 0

#10 Sindorius

Sindorius

    CC Lurker

  • Just Joined
  • Pip
  • 6 posts

Posted 17 March 2011 - 10:36 PM

Wow thanks for all the great responses! And even an entire little program, thanks eafkuor.

When I turned this in only rocketboy responded which was actually the one thing I wasn't thinking about, using an array of pointers to get the job done. My code ended up looking like this
#define BUFLEN  250


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

int	main(void)
{
	auto	char	*strPtr[100];
	auto	char	buf[BUFLEN];
	auto	int	index = 0;
		
	printf("Enter strings: ");
	while (index < 100)
	{
		if ((NULL == fgets(buf, BUFLEN, stdin)) || ('\n' == buf[0]))
		{
		break;
		}
		strPtr[index] = malloc(strlen(buf) + 1);
		strncpy(strPtr[index], buf, strlen(buf) + 1);
		++index;
	}
	for (index--; index >= 0; index--)
	{
		printf("%s", strPtr[index]);
		free(strPtr[index]);
	}
	
	return 0;
}
Obviously some things I see I can touch up on from this thread and what my instructor went over. Also some of it was simply to satisfy the "rules" he wanted us to follow for the program. He also agreed that getting rid of newlines from the string is a good idea. I suppose having command codes and escape sequences embedded in strings is a no-no, which makes sense that you would want to be able to control those aspects of the code.

I'm obviously still the novice in the world of C/C++ but this statement interests me greatly.
	char **strings=malloc(sizeof(char **)*MAX_STRINGS);
It appears you're dynamically allocating memory from the heap for a handler of strings. What I don't get is your argument to the sizeof operator, which I'm sure is merely meant to represent the size of a char. But the "char**" why not just put char? And why use a handler instead of an array of pointers?

Any satisfaction to my curiosity is greatly appreciated. Hope you are all doing well.
  • 0

#11 eafkuor

eafkuor

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 214 posts

Posted 18 March 2011 - 12:57 AM

With that statement, I'm just allocating memory for 100 char ** elements, wich usually occupy 4 bytes in memory (pointers usually take up 4 bytes).
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download