Reputation:
I've been assigned the task of writing a producer/consumer program in C. The Producer process method is below and is trying to capture the vowels from a user-input string (producerString
). I'm having trouble testing to see if the vowelString
was created properly however.
I'm sure the method runs to completion, but nothing is printed when the second printf
is executed. Does it have something to do with how I print the pointer?
char * Producer(char producerString[]) //PRODUCER FUNCTION
{
char *vowelString = (char *) malloc(sizeof(char) * 100);
vowelString = ""; //String used to append vowels to
printf("In Producer with producerString = %s\n", producerString);
for (int i = 0; producerString[i] != '\0'; i++)
{
if (producerString[i] == 'a' || producerString[i] == 'e' || producerString[i] == 'i' || producerString[i] == 'o' || producerString[i] == 'u' || producerString[i] == 'y')
{
int len = strlen(vowelString);
vowelString[len] = i;
vowelString[len + 1] = '\0';
}
else if (producerString[i] == 'p')
{
exit(0);
}
}
printf("In Producer with vowelString = %s\n", vowelString);
return vowelString; //Return vowels string
}
I also try to print it in the Main method after it is returned from the Producer method in the following way:
char *producedString = Producer(inString);
printf("The produced string: %s\n", producedString);
This also doesn't work, but I assume it is a result of the same problem.
Thanks in advance for any help, and any other tips are appreciated.
Upvotes: 0
Views: 55
Reputation: 782488
vowelString = "";
is not how you initialize a dynamically-allocated string. This is assigning the pointer to point to the static literal string, it no longer points to the malloc'ed memory. Literal strings are not modifiable, so you're causing undefined behavior when you write to vowelString[i]
.
Change that line to:
vowelString[0] = '\0';
Also,
vowelString[len] = i;
should be:
vowelString[len] = producerString[i];
But rather than calling strlen()
every time through the loop, you can simply initialize len
to 0
at the beginning of the function, and increment it each time you append a vowel.
char * Producer(char producerString[]) //PRODUCER FUNCTION
{
char *vowelString = (char *) malloc(sizeof(char) * 100);
printf("In Producer with producerString = %s\n", producerString);
int len = 0;
for (int i = 0; producerString[i] != '\0'; i++)
{
if (producerString[i] == 'a' || producerString[i] == 'e' || producerString[i] == 'i' || producerString[i] == 'o' || producerString[i] == 'u')
{
vowelString[len++] = producerString[i];
}
else if (producerString[i] == 'p')
{
exit(0);
}
}
vowelString[len] = '\0';
printf("In Producer with vowelString = %s\n", vowelString);
return vowelString;
}
Upvotes: 2