cutting a string when a character is found - c

I wrote a function that cuts the string "hello world" to "hell" if a 'o' is found.
I keep getting a segmentation fault. I don't know where the mistake could be.
Could anyone help?
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* cutString(char* str, char del){
char *newstring =(char*) str;
malloc(sizeof(char)*strlen(str));
int i= 0;
for(; newstring[i]!='\0'&&newstring[i]!=del;i++);
if(i==strlen(newstring))
printf("not found");
else
newstring[i]='\0';
return newstring;
}
int main(){
cutString("Hello World",'o');
return 0;
}

There are two major problems with your code:
char *newstring =(char*) str makes newstring point to the old str. And since you pass a literal string (which is read only) you will have undefined behavior attempting to modify it.
malloc(sizeof(char)*strlen(str)); is a memory leak. And doesn't allocate space for the terminator.
The crash is probably because point one, when you attempt to modify the read-only string literal.

There are a number of problems in your code. The main problem is that you don't assign the return value from malloc to newstring. Besides that you need to malloc an extra byte for the string termination.
Further, your loop must copy characters from str into newstring.
In main you must assign the return value from the function to a char pointer variable to get hold of the new string.
Something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* cutString(char* str, char del){
char *newstring = malloc(strlen(str) + 1); // malloc into newstring
int i= 0;
while (newstring[i]!='\0' && str[i] != del) // Stop when a) no more chars in str or b) "del" is found
{
newstring[i] = str[i]; // Copy character from str to newstring
++i;
}
newstring[i]='\0'; // Terminate the string
return newstring;
}
int main(){
char* newstring = cutString("Hello World",'o'); // Save the returned value
printf("%s\", newstring);
free(newstring);
return 0;
}

newstring[i]='\0';
This line is invalid. Modifying string literals is undefined behavior. I would suggest check this out :segmentation fault when using pointer
A better solution would be to use arrays instead of pointers

Related

Add a character to a character pointer which is initialized with a string in c [duplicate]

This question already has answers here:
How can I correctly assign a new string value?
(4 answers)
Closed 2 years ago.
I declared a character pointer and allocated memory dynamically and initialized it with a string now i want to add character to the pointer. I tried the following code but it is giving segmentation fault(core dumped) error.
#include <stdio.h>
int main()
{
char *ch;
ch = (char *)malloc(sizeof(char)*32);
ch = "hello";
ch[5] = 'k';
ch[6] = '\0';
printf("%s", ch);
return 0;
}
Yes you have allocated 32 chars for ch pointer. But right on the next line you're reassigning another statically allocated string to it which overrides the pointer to the dynamic memory that was stored in ch.
ch = (char *)malloc(sizeof(char)*32);
ch = "hello";
The result of this is, you lose the handle to the dynamic memory and now you have no way of freeing that memory with free().
If you want to assign "hello" to ch, you can do it with the strcpy function define in <string.h>.
#include <stdio.h>
#include <string.h>
int main()
{
char *ch;
ch = (char *)malloc(sizeof(char)*32);
// ch = "hello";
strcpy(ch, "hello");
ch[5] = 'k';
ch[6] = '\0';
printf("%s", ch);
free(ch);
return 0;
}
Strcpy just iterates through the array and assigns every character one by one. Also never forget to free the dynamic memory allocated.

Truncate string with realloc() in C?

For an assignment i´m asked to change a string str3 containing "Hello World!" to "Hello", and to use realloc() to remove the the exess memory. I dont realy know how to do it.
How do i use realloc() to truncate the string?
How do i change the string from "Hello World!" to "Hello"?
The DString is a char* pointer so DString *str is a double pointer char**.
From the main()function we send str3 containing "Hello World!" and a blanc space to the function shrinkDString().
int main() {
shrinkDString(&str3, ' '); // truncate str3 after the blank, only "Hello" remains
shrinkDString(&str3, ' '); // nothing happens, "Hello" remains the same
}
As pre- and postcondition i´m supposed to use assert(). The DString *str is a double pointer to str3 and ch is a blanc space. Storing "hello World!" in str3 uses 13 memory including \0, "Hello" should only use memory of 6 including \0.
void shrinkDString(DString *str, char ch) {
// Shrinks the DString *str up to the first occurence of ch.
// Precondition: str is not NULL
// Precondition: *str is not NULL
/* Postcondition: if str has been truncated, its new length corresponds to the position of ch in the
original str*/
/* Tips:
- think that str is already allocated in memory and may be changed! Only the proper amount of
memory for storing the truncated string is allocated when the function return
- do not forget the char for ending a string '\0'
- useful C functions: realloc.
*/
}
This is what i´ve tried so far but i get a memory leak when using realloc() and assert(*str != NULL); is dereferencing NULL pointer.
void shrinkDString(DString *str, char ch) {
assert(str != NULL);
assert(*str != NULL);
*str = (char*)realloc(*str, 6);
}
I dont know how to continue. Grateful for any help!
You'd do something like
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s = malloc(100);
strcpy(s, "Hello World!");
printf("1 - s=%p *s = '%s'\n", s, s);
s[5] = '\0';
s = realloc(s, strlen(s)+1);
printf("2 - s=%p *s = '%s'\n", s, s);
return 0;
}
Note that realloc may not actually change the address of the memory block - it may just release the extra space at the end of it, or it may not do anything at all!
Note that this example code doesn't do any of the necessary checking for invalid return values, etc, which you should add.
onlinegdb here
It is not possible only using the realloc. You need also to add the trailing null character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEXT "Hello World"
int main()
{
char *ptr = malloc(strlen(TEXT) + 1);
strcpy(ptr,TEXT);
printf("original string: %s", ptr);
ptr = realloc(ptr, 6);
ptr[5] = 0;
printf("realloced string: %s", ptr);
free(ptr);
return(0);
}
How do i use realloc() to truncate the string?
You don't. A string is terminated by a null byte, and realloc() does not change any of the string's bytes. At least not in any way that you could rely on. The entire effect of a shrinking realloc() is, that it will consider the memory beyond the new size as free and safe for reuse by a future malloc() call. So, for example, the code
char* string1 = strdup("Hello World!");
string1 = realloc(string1, 6);
char* string2 = malloc(7);
printf("%s", string2); //reading uninitialized data, don't do this
might conceivably print "World!". It could print "I've encrypted your harddrive, please pay ***$ in bitcoins..." instead. Whatever. The C standard does not care. It is simply one of the possible things that might happen, that the malloc() call returns the memory that was cut off from string1 with the realloc() call. (Real implementations won't actually print "World!" for reasons which are way beyond this question.)
How do i change the string from "Hello World!" to "Hello"?
You terminate the string with a null byte. That's as simple as
(*str)[5] = 0;
Note the parentheses which force the double pointer to be dereferenced before performing the array subscript operation. Once you have cut down the string like this, you can subsequently also shrink the allocation with realloc():
(*str)[5] = 0;
*str = realloc(*str, 6); //5 characters plus one terminating null byte
the following proposed code:
cleanly compiles
performs the desired functionality
checks for and handles errors
and now, the proposed code:
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void shrinkDString( char **str, char targetChar)
{
char *localStr = *str;
assert(str != NULL);
assert(localStr != NULL);
char *stopChar = strchr( localStr, (int)targetChar );
if( ! stopChar )
{
fprintf( stderr, "target char not in **str\n" );
return;
}
// impllied else, target char found
*stopChar = '\0';
char *temp = realloc( localStr, strlen( localStr ) + 1 );
if( ! temp )
{
perror( "realloc failed" );
exit( EXIT_FAILURE );
}
// implied else, realloc successful
*str = temp;
}

Check chars in a string while using pointers

I want to check each individual char in a string. The string is stored in a pointer.
for some reason I can't, it only let me get the whole string.
here's my code:
int main() {
char *s=(char*)calloc(30,sizeof(char));
s="hello";
printf("%s",&s[2]);
return 0;
}
this code print "llo", i need only 1 char like "l" or "o".
anyone know how i can achieve it?
ty
Use the %c conversion specifier to print a sinlge character instead of %s to print a string.
Also the memory allocation by calloc() is useless, since the pointer to char s get assigned by the address of the first element of the string literal "hello" one statement later.
#include <stdio.h>
int main (void)
{
const char *s = "hello";
printf("%c", s[2]);
return 0;
}
Output:
l
Side Note:
Use the const qualifier to prevent any unintentional write attempts to the string literal that lead to undefined behavior.
If you want to allocate memory and assign/initialize the allocated memory by the string literal "hello", use strcpy() (header string.h):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
char *s = calloc(30, sizeof(*s));
if (!s) // Check if allocation failed.
{
fputs("Error at allocating memory!", stderr);
exit(1);
}
strcpy(s, "hello");
printf("%c", s[2]);
return 0;
}
Output:
l
or you can use strdup() (Note: strdup() is not part of the standard C library) which will automatically allocate memory with the string of the string literal passed as argument initialized:
#include <stdio.h>
#include <string.h>
int main (void)
{
char *s = strdup("hello");
if (!s) // Check if allocation failed.
{
fputs("Error at allocating memory!", stderr);
exit(1);
}
printf("%c", s[2]);
return 0;
}
Side note:
"The string is stored in a pointer."
Something like that is not possible. The pointer points to the first element of the string (literal). The pointer does not store a string.

Truncating string causes segmentation fault

I would like to write a function in C that truncates an input string to 32 chars, but the code below gives me a segmentation fault. Could anyone explain why it is so?
void foo (char *value){
if (strlen(value)>32) {
printf("%c\n", value[31]); // This works
value[31] = '\0'; // This seg faults
}
}
If you call your function like this:
char str[] = "1234567890123456789012345678901234567890";
foo(str);
It will work fine. But if you call it like this:
char *str = "1234567890123456789012345678901234567890";
foo(str);
That can cause a segfault.
The difference here is that in the former case str is a char array, while in the latter case str is a pointer to a string constant. A string constant typically lives in a read only section of memory, so attempting to modify it causes the core dump.
Your program should be something like this :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void foo(char **value) {
if (strlen(*value)>32) {
printf("%c\n", (*value)[32]);
(*value)[32] = '\0'; // You want the string length to be 32, so set 32th character to '\0' so 32 characters will be from 0 to 31
}
}
int main() {
char *str;
str = malloc(100); // Change 100 to max possible length of string user can enter
printf("Enter string : ");
scanf("%s", str);
foo(&str);
printf("Truncated string is %s\n", str);
free(str);
return 0;
}

Terminating a pointer to a pointer?

I get no compiler warning from this but it segfaults. So how can I copy a '\0' at the beginning of the string so I can then use strncat ? (The use of strncpy is not allowed and using memcpy and then terminating the string segfaults also.)
I wrote this to illustrate the problem:
void func(char **str)
{
*str = realloc(*str, -);
*str[0] = '\0'; // I get segfault here.
strncat(*str, -, -);
// memcpy(*str, -, -);
// *str[strlen(*str)] = '\0'; // I get segfault here.
}
int main(void)
{
char *str = NULL;
func(&str);
return 0;
}
EDIT: I meant to write strlen(*str) and not strlen(str). Sorry.
The problem with the second segfaulting line is operator precedence.
[] has higher precedence than *, so *str[strlen(*str)] is interpreted as *(str[strlen(*str)]) - that is, dereference the address pointed to by the memory at str + strlen(*str).
You want (*str)[strlen(*str)] - that is, the character at the end of of str-dereferenced.
Segmentation faults occur when the memory being accessed by the program is invalid. It is very likely that the realloc call was not able to allocate the amount of memory being requested. It is a best practice to check whether the memory is properly allocated before proceeding to access it.
I tried this program and works well in my system.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void func(char **str)
{
*str = realloc(*str, sizeof(char) * 20);
if( *str == NULL)
{
printf("Memory allocation failed\n");
return;
}
*str[0] = '\0';
strncat(*str, "hello world", 11);
//memcpy(*str, "hello world", 11); //memcpy also works fine
//(*str) [strlen(*str)] = '\0';
printf("String : %s\n", *str);
}

Resources