C Program to print string from commandline in reverse [duplicate] - c

This question already has answers here:
Reversing a string in C
(27 answers)
Closed 2 years ago.
/* Pgm to print string from commandline and reverse it */
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main(int argc, char *argv[]) {
if(argc<1){
perror("Not enough arguments");
}
// Printing the string
for(int i=1; i<argc ; i++){
printf("%s\n",argv[i]);
}
//Part to print the string in reverse
char *arr = (char*) malloc(sizeof(argv[1])+1); // +1 for the NULL terminator
strcpy(arr,argv[1]);
char *str = (char*) malloc(sizeof(argv[1])+1); //buffer array
//Reverse part begins
int j=0;
for(int i= sizeof(argv[1]); i>=0 ; i--){
str[j] = arr[i];
j++;
}
for(int j=0;j<sizeof(argv[1]);j++){ // Printing the reverse string
printf("R=%s\n",&str[j]);
}
free(arr);
free(str);
return 0;
}
This program is expected to print the text from argv[1] on commandline in reverse order. But the output I get is weird.
output
user#DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ gcc linex.c -o linex -Wall -pedantic -std=c99
user#DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ ./linex hello
hello
R=
R=
R=
R=
R=olleh
R=lleh
R=leh
R=eh
Also when the input is above a certain number of characters, it automatically truncates it:
user#DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ ./linex strcmpppssdsdssdsd
strcmpppssdsdssdsd
R=spppmcrts
R=pppmcrts
R=ppmcrts
R=pmcrts
R=mcrts
R=crts
R=rts
R=ts
All I want is the output to be : 'olleh' when I type 'hello'

The expression argv[1] has the type char *. That is it is a pointer. sizeof( char * ) that is equivalent to the expression sizeof( argv[1] ) is equal to 4 or 8 depending on the used system.
So for example in this line
char *arr = (char*) malloc(sizeof(argv[1])+1);
there are allocated not enough memory to store a string pointed to by the pointer argv[1]. Instead of the expression sizeof( argv[1] ) you need to use expression strlen( argv[1] ).
Also to output a string in the reverse order there is no any need to allocate dynamically a character array. This is just a bad idea.
Here is a demonstrative program that shows how to output a string in the reverse order.
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *s = "Hello";
for ( size_t i = strlen( s ); i != 0; )
{
putchar( s[--i] );
}
putchar( '\n' );
return 0;
}
The program output is
olleH
If you want not just to output a string in the reverse order but to create a new string in the reverse order then what you need is to write a function that performs copying of a string stored in one character array into another character array.
Here is a demonstrative program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * copy_reverse( char *s1, const char *s2 )
{
size_t n = strlen( s2 );
s1[n] = '\0';
while ( *s2 ) s1[--n] = *s2++;
return s1;
}
int main(void)
{
const char *s1 = "Hello";
char *s2 = malloc( strlen( s1 ) + 1 );
if ( s2 ) puts( copy_reverse( s2, s1 ) );
free( s2 );
return 0;
}
The program output is the same as shown above
olleH

Related

Completing a function using pointers

one of the assignments in my class has this objective:
Complete CapVowels(), which takes a string as a parameter and returns a new string containing the string parameter with the first occurrence of each of the five English vowels (a, e, i, o, and u) capitalized.
Hint: Begin CapVowels() by copying the string parameter to a newly allocated string.
Ex: If the input is:
management
the output is:
Original: management
Modified: mAnagEment
This is the current code I have, and I will highlight the section I'm supposed to complete:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
**// Return a newly allocated copy of original
// with the first occurrence of each vowel capitalized
char* CapVowels(char* original) {
return CapVowels(*original= "A.E,I,O,U");
}**
int main(void) {
char userCaption[50];
char* resultStr;
scanf("%s", userCaption);
resultStr = CapVowels(userCaption);
printf("Original: %s\n", userCaption);
printf("Modified: %s\n", resultStr);
// Always free dynamically allocated memory when no longer needed
free(resultStr);
return 0;
}
The section with the ** meaning it's bolded is the section I'm supposed to complete before the int main(void). I can't figure out how to complete the objective. I get mixed up with pointers and dereferencing and, I tried dereferencing when returning the function so that the value will come out to what it's supposed to. I understand one part of it, but I don't know how you would complete it to output to the required output:
Original: management
Modified: mAnagEment
Hint: Begin CapVowels() by copying the string parameter to a newly allocated string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Return a newly allocated copy of original
// with the first occurrence of each vowel capitalized
char* CapVowels(const char* original) {
char* result = strcpy(malloc(strlen(original+1)), original);
char* vowels = "aeiou";
while(*vowels)
{
char* ptr = strchr(result, *vowels);
(ptr)? *ptr = toupper(*ptr) : vowels++;
}
return result;
}
int main(void) {
char userCaption[50];
char* resultStr;
scanf("%s", userCaption);
resultStr = CapVowels(userCaption);
printf("Original: %s\n", userCaption);
printf("Modified: %s\n", resultStr);
// Always free dynamically allocated memory when no longer needed
free(resultStr);
return 0;
}
Output
Success #stdin #stdout 0s 5424KB
Original: management
Modified: mAnAgEmEnt
You can use strlen to get the length of the input, then use malloc to allocate enough space for the result. Then, just loop over the input until the terminating null character ('\0'), incrementally assigning the current character to the result if it is a consonant or the uppercase version if it is a vowel (using the toupper function).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *CapVowels(char *original){
if (!original)
return NULL;
const char *vowels = "aeiou";
size_t len = strlen(original); // get length of input (terminating '\0' not included)
char *result = malloc(len + 1); // allocate memory for new string (note that sizeof(char) is 1)
for (char *dest = result; *original; ++original)
*dest++ = strchr(vowels, *original) // check if current character is in the vowels
? toupper(*original) : *original;
result[len] = '\0';
return result;
}
Here's a version that works even with multiple words in 'original'.
char *CapVowels( const char *original ) {
char *cp, *out = strdup( original );
for( char *vowels = "aeiou"; *vowels; vowels++ ) {
if( ( cp = strchr( out, *vowels ) ) != NULL )
*cp = toupper( *cp );
}
return out;
}
void main( void ) {
char userCaption[50];
gets( userCaption );
char *capped = CapVowels( userCaption );
printf( "Original: %s\n", userCaption );
printf( "Modified: %s\n", capped );
free( capped );
}

Getting no output why is that?

I', learning C and I'm getting no output for some reason, probably I don't return as I should but how I should? (described the problem in the comments below :D)
Any help is appreciated!
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char *makeUpperCase (char *string);
int main()
{
printf(makeUpperCase("hello")); //Here there is no output, and when I'm trying with the format %s it returns null
return 0;
}
char *makeUpperCase(char *string)
{
char str_out[strlen(string) + 1];
for (int i = 0; i < strlen(string); ++i)
str_out[i] = toupper(string[i]);
printf(str_out); //Here I get the output.
return str_out;
}
You declared within the function a local variable length array that will not be alive after exiting the function
char str_out[strlen(string) + 1];
So your program has undefined behavior.
If the function parameter declared without the qualifier const then it means that the function changes the passed string in place. Such a function can be defined the following way
char * makeUpperCase( char *string )
{
for ( char *p = string; *p != '\0'; ++p )
{
*p = toupper( ( unsigned char )*p );
}
return string;
}
Otherwise you need to allocate dynamically a new string. For example
char * makeUpperCase( const char *string )
{
char *str_out = malloc( strlen( string ) + 1 );
if ( str_out != NULL )
{
char *p = str_out;
for ( ; *string != '\0'; ++string )
{
*p++ = toupper( ( unsigned char )*string );
}
*p = '\0';
}
return str_out;
}
Here is a demonstration program.
#include <stdop.h>
#include <stdlib.h>
#include <string.h>
char *makeUpperCase( const char *string )
{
char *str_out = malloc( strlen( string ) + 1 );
if (str_out != NULL)
{
char *p = str_out;
for (; *string != '\0'; ++string)
{
*p++ = toupper( ( unsigned char )*string );
}
*p = '\0';
}
return str_out;
}
int main( void )
{
char *p = makeUpperCase( "hello" );
puts( p );
free( p );
}
The program output is
HELLO
The problem is that printf() is buffering output based on a bit complex mechanism. When you are outputting to a terminal, printf() just buffers everything until the buffer fills (which is not going to happen with just the string "hello", or until it receives a '\n' character (which you have not used in your statement)
So, to force a buffer flush, just add the following statement
fflush(stdout);
after your printf() call.

Assert is failing in a string array comparison [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 3 years ago.
In this part of my code I remove white spaces of string1 and copy the result to string2.
char * remove_blank_spaces(char * string1) {
char * string2 = malloc(sizeof(string1));
int index = 0;
for (int i = 0; string1[i] != 0; i++) {
if(string1[i] != ' ') {
//printf("i: %d\n", i);
//printf("c2: %c\n", string1[i]);
string2[index] = string1[i];
index++;
}
}
string2[index] = '\0';
printf("string2: %s\n", string2);
return string2;
}
I check the result with:
assert(remove_blank_spaces("a b") == "ab"); // Edit: here is the error!
I got an error: Assertion failed! and Expression: remove_blank_spaces("a b") == "ab"
I compared the strings in Virtual-C and they look the same.
Why the assertion is failing?
Your code has a bug: malloc allocates insufficient space, and this results in undefined behaviour when trying to access unallocated memory.
The assertion is also failing because you are comparing pointers via ==, instead of C strings via strcmp.
Furthermore, I suggest making two changes:
Don’t mix computation and output. Return the value, don’t printf it inside the function.
Use descriptive and correct names. This requires taking context into account. For instance, index can generally be a good name, but in your case it’s unclear which index you’re referring to, and this invites errors, where index is used to index into the wrong variable. As for “correct” names, what you call “blank space” is more conventionally known as “whitespace”.
To improve the second point, I suggest actually changing the implementation and, instead of having a second index variable, to iterate over the output using a pointer. There are other possibilities, but this one has the advantage that accidentally indexing using the wrong variable is impossible.
Taking this together, we get
char *remove_whitespace(const char *str) {
char *result = malloc(strlen(str) + 1);
char *out = result;
for (size_t i = 0; str[i] != '\0'; i++) {
if (str[i] != ' ') {
*out++ = str[i];
}
}
*out = '\0';
return result;
}
We could additionally do away with the i loop counter. Unfortunately the result is less readable, not more, because we would need to increment str at the end of the loop, and this would leave us with an unsightly for (; *str != '\0'; str++) loop construct.
For starters this function declaration
char * remove_blank_spaces(char * string1) {
is incorrect and only confuses users of the function. If within the function you are creating a new character array then the parameter shall have the qualifier const.
char * remove_blank_spaces( const char * string1) {
Otherwise the function should change the original string "in-place".
This call
char * string2 = malloc(sizeof(string1));
also is incorrect. I think you mean
char * string2 = malloc( strlen( string1 ) + 1 );
But even this call is not very good because the result string can be much less than the original string.
So at first you should count the numb er of characters in the result string and only then allocate the memory.
This assert is also incorrect
assert(remove_blank_spaces("a b") == "ab");
In this expression there are compared addresses of two string: the first one is the string returned by the function and the second one is the string literal.
Even if you will write an expression like this
assert( "ab" == "ab");
the value of the expression can be equal either to logical true or false depending on the compiler option that specifies whether equal string literals are stored as one string literal or occupy different extents of memory.
You should write instead
assert( strcmp( remove_blank_spaces("a b"), "ab" ) == 0 );
Take into account that it is reasonable also to consider trhe tab character '\t' in the if statement like
if(string1[i] != ' ' && string1[i] != '\t') {
Or you could use the standard function isblank.
Here is a demonstrative program
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <string.h>
char * remove_blank_spaces( const char *s )
{
size_t n = 0;
for ( size_t i = 0; s[i] != '\0'; i++ )
{
if ( !isblank( ( unsigned char )s[i] ) ) ++n;
}
char *result = malloc( n + sizeof( ( char )'\0' ) );
char *p = result;
do
{
if ( !isblank( ( unsigned char )*s ) )
{
*p++ = *s;
}
} while ( *s++ != '\0' );
return result;
}
int main(void)
{
const char *s1 = "a b";
char *s2 = remove_blank_spaces( s1 );
assert( strcmp( s1, s2 ) == 0 );
puts( s2 );
free( s2 );
return 0;
}
The program output is
ab
Pay attention to that instead of the type int as it is shown in other answers you should use the type size_t for the variables index and i because it is the type that is used with string lengths and indices and by the function malloc. The type int is not large enough to store size of strings.
If you indeed want to declare the function like
char * remove_blank_spaces( char *s )
that is when the parameter does not have the qualifier const then you shall not allocate dynamically a new character array within the function and the function itself can look much simpler.
Here is a demonstrative program.
#include <stdio.h>
#include <assert.h>
#include <string.h>
char * remove_blank_spaces( char *s )
{
char *destination = s;
char *source = s;
do
{
if ( *source != ' ' && *source != '\t' )
{
*destination++ = *source;
}
} while ( *source++ != '\0' );
return s;
}
int main(void)
{
char s[] = "a b";
remove_blank_spaces( s );
assert( strcmp( s, "ab" ) == 0 );
puts( s );
return 0;
}
Its output is
ab

Segmentation fault on strcat

I have recently begun working on learning the C language and have repeatedly run into an error in which calling the strcat function from the <string.h> module results in a segmentation fault. I've searched for the answers online, including on this stackoverflow post, without success. I thought this community might have a more personal insight into the problem, as the general solutions don't seem to be working. Might be user error, might be a personal issue with the code. Take a look.
#include <stdio.h>
#include <string.h>
char * deblank(const char str[]){
char *new[strlen(str)];
char *buffer = malloc(strlen(new)+1);
for (int i=0; i<strlen(*str); i++){
if(buffer!=NULL){
if(str[i]!=" "){
strcat(new,str[i]); //Segmentation fault
}
}
}
free(buffer);
return new;
}
int main(void){
char str[] = "This has spaces in it.";
char new[strlen(str)];
*new = deblank(str);
puts(new);
}
I've placed a comment on the line I've traced the segmentation fault back to. The following is some Java to make some sense out of this C code.
public class deblank {
public static void main(String[]args){
String str = "This has space in it.";
System.out.println(removeBlanks(str));
}
public static String removeBlanks(String str){
String updated = "";
for(int i=0; i<str.length(); i++){
if(str.charAt(i)!=' '){
updated+=str.charAt(i);
}
}
return updated;
}
}
Any insights into this error will be much appreciated. Please point out typos as well... I've been known to make them. Thanks.
OK, let's do this.
#include <stdio.h>
#include <string.h>
char * deblank(const char str[]){
char *new[strlen(str)];
^ This line creates an array of pointers, not a string.
char *buffer = malloc(strlen(new)+1);
malloc is undeclared. Missing #include <stdlib.h>. Also, you should check for allocation failure here.
strlen(new) is a type error. strlen takes a char * but new is (or rather evaluates to) a char **.
for (int i=0; i<strlen(*str); i++){
strlen(*str) is a type error. strlen takes a char * but *str is a char (i.e. a single character).
i<strlen(...) is questionable. strlen returns size_t (an unsigned type) whereas i is an int (signed, and possibly too small).
Calling strlen in a loop is inefficient because it has to walk the whole string to find the end.
if(buffer!=NULL){
This is a weird place to check for allocation failure. Also, you don't use buffer anywhere, so why create/check it at all?
if(str[i]!=" "){
str[i]!=" " is a type error. str[i] is a char whereas " " is (or rather evaluates to) a char *.
strcat(new,str[i]); //Segmentation fault
This is a type error. strcat takes two strings (char *), but new is a char ** and str[i] is a char. Also, the first argument to strcat must be a valid string but new is uninitialized.
}
}
}
free(buffer);
return new;
new is a local array in this function. You're returning the address of its first element, which makes no sense: As soon as the function returns, all of its local variables are gone. You're returning an invalid pointer here.
Also, this is a type error: deblank is declared to return a char * but actually returns a char **.
}
int main(void){
char str[] = "This has spaces in it.";
char new[strlen(str)];
*new = deblank(str);
This is a type error: *new is a char but deblank returns a char *.
puts(new);
puts takes a string, but new is essentially garbage at this point.
}
You can't use strcat like you did, it is intended to catenate a C-string at the end of another given one. str[i] is a char not a C-string (remember that a C-string is a contiguous sequence of chars the last being the NUL byte).
You also cannot compare strings with standard comparison operators, if you really need to compare strings then there is a strcmp function for it. But you can compare chars with standard operators as char is just a kind of integer type.
This should do the trick:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * deblank(const char str[]) {
char *buffer = malloc(strlen(str)+1); // allocate space to contains as much char as in str, included ending NUL byte
for (int i=0, j=0; i<strlen(str)+1; i++) { // for every char in str, included the ending NUL byte
if (str[i]!=' ') { // if not blank
buffer[j++] = str[i]; // copy
}
}
return buffer; // return a newly constructed C-string
}
int main(void){
char str[] = "This has spaces in it.";
char *new = deblank(str);
puts(new);
free(new); // release the allocated memory
}
So, not sure whether this helps you, but a C code doing the same as your Java code would look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *removeBlanks(const char *str)
{
char *result = malloc(strlen(str) + 1);
if (!result) exit(1);
const char *r = str;
char *w = result;
while (*r)
{
// copy each character except when it's a blank
if (*r != ' ') *w++ = *r;
++r;
}
*w = 0; // terminate the result to be a string (0 byte)
return result;
}
int main(void)
{
const char *str = "This has spaces in it.";
char *new = removeBlanks(str);
puts(new);
free(new);
return 0;
}
I would'nt recommend to name a variable new ... if you ever want to use C++, this is a reserved keyword.
I tried compiling with warnings enabled, here are some you should fix.
You need to include stdlib.h
char *new[strlen(str)] creates an array of char* not of char, so not really a string. Change it to char new[strlen(str)].
To check if str[i] is a space, you compare it to the space character ' ', not a string whose only character is a space " ". So change it to str[i]!=' '
strcat takes a string as the second argument and not a character, like you're giving it with str[i].
Also, what are you using buffer for?
Another mistake, is that you probably assumed that uninitialized arrays take zero values. The new array has random values, not zero/null. strcat concatenates two strings, so it would try to put the string in its second argument at the end of the first argument new. The "end" of a string is the null character. The program searches new for the first null character it can find, and when it finds this null, it starts writing the second argument from there.
But because new is uninitialized, the program might not find a null character in new, and it would keep searching further than the length of new, strlen(str), continuing the search in unallocated memory. That is probably what causes the segmentation fault.
There can be three approaches to the task.
The first one is to update the string "in place". In this case the function can look something like the following way
#include <stdio.h>
#include <ctype.h>
#include <iso646.h>
char * deblank( char s[] )
{
size_t i = 0;
while ( s[i] and not isblank( s[i] ) ) ++i;
if ( s[i] )
{
size_t j = i++;
do
{
if ( not isblank( s[i] ) ) s[j++] = s[i];
} while( s[i++] );
}
return s;
}
int main(void)
{
char s[] = "This has spaces in it.";
puts( s );
puts( deblank( s ) );
return 0;
}
The program output is
This has spaces in it.
Thishasspacesinit.
Another approach is to copy the source string in a destination character array skipping blanks.
In this case the function will have two parameters: the source array and the destination array. And the size of the destination array must be equal to the size of the source array because in general the source array can not have blanks.
#include <stdio.h>
#include <ctype.h>
#include <iso646.h>
char * deblank( char *s1, const char *s2 )
{
char *t = s1;
do
{
if ( not isblank( *s2 ) ) *t++ = *s2;
} while ( *s2++ );
return s1;
}
int main(void)
{
char s1[] = "This has spaces in it.";
char s2[sizeof( s1 )];
puts( s1 );
puts( deblank( s2, s1 ) );
return 0;
}
The program output will be the same as shown above.
Pay attention to this declaration
char s2[sizeof( s1 )];
The size of the destination string in general should be not less than the size of the source string.
And at last the third approach is when inside the function there is created dynamically an array and pointer to the first element of the array is returned from the function.
In this case it is desirable at first to count the number of blanks in the source array that to allocated the destination array with the appropriate size.
To use the functions malloc and free you need to include the following header
#include <stdlib.h>
The function can be implemented as it is shown in the demonstrative program.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <iso646.h>
char * deblank( const char *s )
{
size_t n = 1; /* one byte reserved for the terminating zero character */
for ( const char *t = s; *t; ++t )
{
if ( not isblank( *t ) ) ++n;
}
char *s2 = malloc( n );
if ( s2 != NULL )
{
char *t = s2;
do
{
if ( not isblank( *s ) ) *t++ = *s;
} while ( *s++ );
}
return s2;
}
int main(void)
{
char s1[] = "This has spaces in it.";
char *s2 = deblank( s1 );
puts( s1 );
if ( s2 ) puts( s2 );
free( s2 );
return 0;
}
The program output is the same as for the two previous programs.
As for the standard C function strcat then it cats two strings.
For example
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[12] = "Hello ";
char *s2 = "World";
puts( strcat( s1, s2 ) );
return 0;
}
The destination array (in this case s1) must have enough space to be able to append a string.
There is another C function strncat in the C Standard that allows to append a single character to a string. For example the above program can be rewritten the following way
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[12] = "Hello ";
char *s2 = "World";
for ( size_t i = 0; s2[i] != '\0'; i++ )
{
strncat( s1, &s2[i], 1 );
}
puts( s1 );
return 0;
}
But it is not efficient to use such an approach for your original task because each time when the function is called it has to find the terminating zero in the source string that to append a character.
you can try recursively
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void deblank(const char* str, char *dest) {
if (!*str) {*dest = '\0';return;}
// when we encounter a space we skip
if (*str == ' ') {
deblank(str+1, dest);
return;
}
*dest = *str;
deblank(str+1, dest+1);
}
int main(void) {
const char *str = "This has spaces in it.";
char *output = malloc(strlen(str)+1);
deblank(str, output);
puts(output);
free(output);
}

C Program that stores an unknown number of strings of unknown sizes from user - Heap block at 00558068 modified at 00558096 past requested size of 26

I'm trying to write a program in C that takes an unknown number of strings (each of unknown size) from the user as input and stores them then prints them when the user has finished entering strings.
First I use a pointer that points to character pointers (char** strings) and allocate 1 char* sized block of memory to it with malloc. I then allocate 1 char sized block to the pointer that strings is pointing to ( (strings) ) with malloc also. From there I take a string input from the user using a user-defined function called get_String() and place it into the char pointer that char* string is pointing to. I then use a for loop to continue allocating an extra char* of memory to char** strings and 1 char of memory to the new pointer.
However, I keep experiencing an error on the 2nd iteration of the for loop, on the line strings = (char**) realloc (strings, index+1); and I receive the error message: Heap block at 00558068 modified at 00558096 past requested size of 26. It seems like I am writing past the allocated memory to char** strings, but I don't know where or how I am doing this.
Here is my entire code:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
void get_strings( char* strings); // function to take in a string of an unknown size
int main( void )
{
char** strings;
int index, count;
(strings) = (char**) malloc( sizeof(char*)); // this is the pointer that holds the addresses of all the strings
*strings = (char*) malloc( sizeof(char)); // the address of the first string
printf( "Enter a list of stringss. Quit by pressing enter without entering anything\n" );
get_strings( *strings );
for( index = 1; strlen(*(strings+index-1))!=1; index++) // stores strings from the user until they enter a blank line which is detected when string length is 1 for the \n
{
strings = (char**) realloc (strings, index+1); // adds an extra character pointer for another string
*(strings + index) = (char*) malloc(sizeof(char)); // allocates memory to the new character pointer
get_strings( *(strings + index) ); // stores the string from the user
}
printf( "You entered:\n" );
for( count = 0; strlen(*(strings + count)) != 1; count++ ) //prints every string entered by the user except for the terminating blank line
{
printf( "%s", *(strings + count ) );
free( *(strings + count ));
}
free( strings );
system( "PAUSE" );
return 0;
}
void get_strings( char* strings )
{
fgets( strings, 1, stdin );
while( strings[ strlen( strings ) - 1 ] != '\n' )
{
strings = (char*) realloc( strings, strlen(strings)+2 );
fgets( strings + strlen(strings), 2, stdin );
}
}
As stated before, heap block occurs on the second iteration of the for loop while executing the line: strings = (char**) realloc (strings, index+1);
for( index = 1; strlen(*(strings+index-1))!=1; index++) // stores strings from the user until they enter a blank line which is detected when string length is 1 for the \n
{
strings = (char**) realloc (strings, index+1); // error occurs here
*(strings + index) = (char*) malloc(sizeof(char)); // allocates memory to the new character pointer
I would very much appreciate it if someone could explain to me the cause of this error and a direction to fix it. Thank you.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *get_strings(void);
int main( void ){
char **strings = NULL;
char *string;
int index, count;
printf( "Enter a list of stringss. Quit by pressing enter without entering anything\n" );
for(index = 0; string = get_strings(); ++index){
strings = (char**) realloc (strings, (index+1)*sizeof(*strings));
strings[index] = string;
}
printf( "You entered:\n" );
for( count = 0; count < index; ++count ){
printf("%s\n", strings[count]);
free( strings[count] );
}
free( strings );
system( "PAUSE" );
return 0;
}
char *get_strings(void){
char *string = NULL;//or calloc(1,sizeof(char)) for return "" (test by caller: *string == '\0')
int ch;
size_t len = 0;
while(EOF != (ch=fgetc(stdin)) && ch != '\n' ) {
string = (char*)realloc( string, len + 2);//To realloc to each character is inefficient
string[len++] = ch;
}
if(string)
string[len] = '\0';
return string;//The value is NULL when there is no input substantial.
}

Resources