string updating in c - c

this is a sample program demonstrating getting a string value from a func
can allocate memory inside called function itself and return
can allocate memory inside calling function and called function just updates it.
i am facing problem with the 2nd way.
is there any workaround?
/*
* main.c
*
* Created on: Sep 6, 2014
* Author: Murtaza
*/
#include<stdio.h>
#include<stdlib.h>
char* someFunc1();
void someFunc2(char* str);
void firstApproach();
void secondApproach();
int main()
{
firstApproach();
printf("\n");
secondApproach();
return 0;
}
char* someFunc1()
{
char *str = (char*)malloc(sizeof(char)*10);
str = "HELLO";
return str;
}
void someFunc2(char* str)
{
str = "Hello";
}
void secondApproach()
{
char *str = (char*)malloc(sizeof(char)*10);
someFunc2(str);
printf(str);
printf("heythere");
}
void firstApproach()
{
char *str;
str=someFunc1();
printf(str);
printf("wassup");
}
Please tell me why the second approach isn't working.
thanks!
my output is:
HELLOwassup
h>heythere
and my expected output should be
HELLOwassup
Helloheythere

void someFunc2(char* str)
{
str="Hello"; //-----the variable str is local to this function, thus it goes out of scope as
// soon as the function returns
}
void secondApproach()
{
char *str=(char*)malloc(sizeof(char)*10);
someFunc2(str);
printf(str); // -------------- here the value inside str is some garbage value.
printf("heythere");
}
CORRECTION :
void someFunc2(char **str )
{
*str = "hello";
}
void secondApproach()
{
char *str=(char*)malloc(sizeof(char)*10);
someFunc2(&str); // pass the address of the string
printf("%s", str);
printf("heythere");
}

Let's take a closer look at someFunc2:
void someFunc2(char* str)
{
/* str is a copy of the pointer that was passed in from secondApproach(). */
str = "Hello";
}
Here, you are passing a pointer by value. Thus, str in someFunc2 is a copy of the original pointer str that was passed in from secondApproach(). someFunc2 tells the copy pointer to point somewhere else, but it leaves the original str pointer alone. The solution is to pass in the address of the str pointer then tell someFunc2 to modify the pointer at that address to point to "hello".
void secondApproach()
{
char* str = (char*) malloc(sizeof(char) * 10);
someFunc2(&str); // Pass in the address of str.
printf("%s", str);
printf("heythere");
}
void someFunc2(char** str)
{
*str = "hello";
}

When you write a string between quotes and use it directly as:
a char* -> it gets created in a mutable place in memory, and gives its address to the pointer variable its assigned to. It is still in memory as long as that variable referencing it is not NULL.
an argument -> it gets created as char* and passed to the function (and treated there as a char*), then automatically disposed from memory (i.e. you can't access it or reference it anymore) ..
So, the only situation when a string is actually mutable is when you assign it to a char[], then it gets created in readonly memory and copied into to the stack .. ( the copy on the stack is what the char[] variable will point to )
If you think about it for some time, you realize that this is one of the benefits of dynamic memory: you can create a char* that is mutable, and since it is just a pointer, you don't need to specify the size of the string it is going to point at. So you can see how useful this would be ..
Also, it's worth to note that in functions:
if you pass a string, the variable in the function itself is treated as a char pointer and most likely would try to modify it, and if it's readonly that would raise a Segmentation Fault. So functions are assuming you know what you're doing ..
if you want a function to be able to modify a string directly (i.e string = "somestring") then pass it a pointer to the actual string, else the modification will only be local to the function. That's because the string is a "pointer to char", so the function can't modify the string as a whole. But that also means that a function can modify the string's characters individually ( obviously, because it has a pointer for characters: the string ). If you pass it, however, a string pointer (char**), the function can modify the string directly (*string = "whatever") and can also modify the characters individually (*string[1] = 'C'). Which choice you need depends entirely on the purpose of the function ..
Now, for your specific example, you can do one of two ..
Using a pointer to a pointer to a char (string pointer)
void someFunc2(char** str)
{
*str = "Hello";
}
Using a pointer to char (string)
void someFunc2(char* str)
{
char *k = "Hello";
for(int i = 0; i < 5; ++i)
str[i] = k[i];
}
This is one of the most controversial and advanced topics in C. No matter what type of C programming you're doing, you have to understand these core concepts ..

Related

How to write to char* from a function in C

I am struggling to write a char* passed as an argument. I want to write some string to char* from the function write_char(). With the below code, I am getting a segmentation fault.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void write_char(char* c){
c = (char*)malloc(11*(sizeof(char)));
c = "some string";
}
int main(){
char* test_char;
write_char(test_char);
printf("%s", test_char);
return 0;
}
You have two problems (related to what you try to do, there are other problems as well):
Arguments in C are passed by value, which means that the argument variable (c in your write_char function) is a copy of the value from test_char in the main function. Modifying this copy (like assigning to it) will only change the local variables value and not the original variables value.
Assigning to a variable a second time overwrites the current value in the variable. If you do e.g.
int a;
a = 5;
a = 10;
you would (hopefully) not wonder why the value of a was changed to 10 in the second assignment. That a variable is a pointer doesn't change that semantic.
Now how to solve your problem... The first problem could be easily solved by making the function return a pointer instead. And the second problem could be solved by copying the string into the memory instead of reassigning the pointer.
So my suggestion is that you write the function something like
char *get_string(void)
{
char *ptr = malloc(strlen("some string") + 1); // Allocate memory, +1 for terminator
strcpy(ptr, "some string"); // Copy some data into the allocated memory
return ptr; // Return the pointer
}
This could then be used as
char *test_string = get_string();
printf("My string is %s\n", test_string);
free(test_string); // Remember to free the memory we have allocated
Within the function
void write_char(char* c){
c = (char*)malloc(11*(sizeof(char)));
c = "some string";
}
the parameter c is a local variable of the function. Changing it within the function does not influence on the original argument because it is passed by value. That is the function deals with a copy of the original argument.
You have to pass the argument by reference through pointer to it.
Also the function has a memory leak because at first the pointer was assigned with the address of the allocated memory and then reassigned with the address of the first character of the string literal "some string".
If you want to create a copy of a string literal then what you need is the following
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void write_char( char **s )
{
const char *literal = "some string";
*s = malloc( strlen( literal ) + 1 );
if ( *s ) strcpy( *s, literal );
}
int main( void )
{
char *test_char = NULL;
write_char( &test_char );
if ( test_char ) puts( test_char );
free( test_char );
}
The program output is
some string
Do not forget to allocate dynamically a character array that is large enough to store also the terminating zero of the string literal.
And you should free the allocated memory when the allocated array is not needed any more.
If you want just to initialize a pointer with the address of a string literal then there is no need to allocate dynamically memory.
You can write
#include <stdio.h>
void write_char( char **s )
{
*s = "some string";
}
int main( void )
{
char *test_char = NULL;
write_char( &test_char );
puts( test_char );
}
In C, you'll need to pass a pointer to a pointer. Your malloc call is trying to change the value of the variable that's being passed in, but it's actually only a copy. The real variable you pass in will not be changed.
Also, the way that you copy a string into a char* is not using assignment... Here's some revised code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void write_char(char** c){
size_t len = strlen("some string");
*c = (char*)malloc(len + 1); // + 1 for null termination
strncpy(*c, "some string", len);
}
int main(){
char* test_char;
write_char(&test_char);
printf("%s", test_char);
return 0;
}
String assignment in C is very different from most modern languages. If you declare a char * and assign a string in the same statement, e.g.,
char *c = "some string";
that works fine, as the compiler can decide how much memory to allocate for that string. After that, though, you mostly shouldn't change the value of the string with =, as this use is mostly for a constant string. If you want to make that especially clear, declare it with const. You'll need to use strcpy. Even then, you'll want to stay away from declaring most strings with a set string, like I have above, if you're planning on changing it. Here is an example of this:
char *c;
c = malloc(16 * sizeof(char));
strcpy(c, "Hello, world\n");
If you're passing a pointer to a function that will reallocate it, or even malloc in the first place, you'll need a pointer to a pointer, otherwise the string in main will not get changed.
void myfunc(char **c) {
char *tmp = realloc(*c, 32 * sizeof(char));
if(tmp != NULL) {
*c = tmp;
}
}
char *c = malloc(16 * sizeof(char));
strcpy(c, "Hello, world\n");
myfunc(&c);
char* test_char="string"; // initialize string at the time of declaration
void write_char(char* c){
c = (char*)malloc(11*(sizeof(char)));
}
int main(){
char* test_char="strin";
write_char(test_char);
printf("%s", test_char);
return 0;
}

Changing the value of a string with a pointer in C

I was trying to change the value of the string t_string by passing a pointer of the string to a function and then changing the value of that pointer in the function.
The output I am receiving is the original string "Hello".
Any help would be greatly appreciated :) Thanks!
#include <stdio.h>
#include "string.h"
void editString(char *theString);
int main() {
char t_string[] = "Hello\n";
char *s = t_string;
editString(s);
printf("The string after: %s", t_string);
return 0;
}
void editString(char *theString){
theString = "Good Bye\n";
}
In C, parameters are pass by value. What you're doing is changing the value of the local variable theString to point to a string literal. That local variable change is not reflected in the calling function.
To change what theString points to, use strcpy. That will follow what theString points to (i.e. the array in main). Note however that the array isn't large enough to hold the new string, so if you do that you will write past the end of the array and invoke undefined behavior. So you need to make the array large enough to hold either string.
int main() {
char t_string[20] = "Hello\n"; // enlarge array to hold either string
char *s = t_string;
editString(s);
printf("The string after: %s", t_string);
return 0;
}
void editString(char *theString){
strcpy(theString, "Good Bye\n"); // use strcpy
}
Array designators are non-modifiable lvalues. So you can not change an array such a way.
In this statement
char *s = t_string;
there is created a new object with the name s that is initialized by the address of the first character of the array t_string.
In this call
editString(s);
there is created a copy of the value of the argument that is assigned to the function parameter.
You can imagine the function definition and its call the following way
editString(s);
//...
void editString(/*char *theString*/){
char *theString = s;
theString = "Good Bye\n";
}
So even the argument s is not changed by the function. That is at first the local variable theString initialized by the value stored in the argument s and then this local variable is reassigned by the address of the first character of the string literal "Good Bye\n".
Neither the array t_string nor the pointer s defined in main were changed in the function.
If you want to change the array you have to assign its characters individually for example by using the standard string function strcpy declared in header <string.h>. The array has to have enough size to accommodate the new string literal.
For example
#include <stdio.h>
#include "string.h"
void editString(char *theString);
int main( void )
{
char t_string[10] = "Hello\n";
char *s = t_string;
editString(s);
printf("The string after: %s", t_string);
return 0;
}
void editString(char *theString){
strcpy( theString, "Good Bye\n" );
}
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )

Changing the value of what a pointer is pointing to in C

I am getting a pointer to a string passed as an argument to the function, and I need to change a few characters in the string. I'm copying the string to a char array and editing what I need to just fine, but I need to change the original string that is being pointed to into the new char[] I just created.
The function has to return void, and because the pointer being passed is just a copy of the one from main, setting it to point to the new char[] won't do anything as it will just be deleted when the function ends, so I need to actually change the string being pointed to.
*str = &newstr[0]
This is giving me the compiler error: assignment makes integer from pointer without a cast.
*str = newstr
And this is segfaulting when I run the program.
Here is the full function:
void replace(char* str, char toReplace, char replaceWith) {
int strLen = strlen(src);
char newstr[strLen];
int i;
for (i = 0; i < strLen; i++) {
if (str[i] == toReplace)
newstr[i] = replaceWith;
else
newstr[i] = str[i];
}
// How to change the value of the string being pointed to by *str to now be newstr?
}
After digesting all the comments on your question, I've come to the understanding that you're trying to invoke your function in the following manner:
char * str = "string literal"; /* compiler should have warned you about assigning
string literal to non-const pointer. */
replace( str, 'i', 'u' );
printf( "%s\n", str );
Now, the problem with that is any attempts to modify the memory that str points to will be undefined behaviour.
Your attempt at a solution was to try to change the actual pointer inside the function. But to do so, your replace function would need to accept a char**, and then allocate new memory. That's not a nice approach in this case. You really just need to modify the string in-place:
void replace(char* str, char toReplace, char replaceWith)
{
while( *str )
{
if( *str == toReplace ) *str = replaceWith;
str++;
}
}
And how to deal with the string literal? Well, the solution is simple. Make an array:
char str[] = "string literal";
replace( str, 'i', 'u' );
printf( "%s\n", str );
How to change the value of the string being pointed to by *str to now
be newstr?
You can't due to (1) the way you pass str to the function as char *s and (2) because you declare newstr as a local variable in replace. (and probably for a whole host of other reasons that are not ascertainable from the limited section of code you posted)
When you pass a pointer to a function, the function receives a copy of the pointer with it very own and very different memory address. In other words when you declare the parameter char *str in your function parameter list, that creates a new pointer. (it still points to whatever is passed in str, but its variable address is very different from the original pointer address in the calling function - so nothing you do to the address of str will ever be reflected in the calling function.) If you want to assign a new address to a pointer in a function, you must pass the original address from the caller. e.g.
void replace(char **str, char toReplace, char replaceWith)
and then in your calling routine call it with:
replace (&origPtr, char toReplace, char replaceWith)
(as a style aside: don't use CamelCase variables in C, camelcase is proper)
Finally, since the address for newstr will be destroyed when you exit function replace, your only option for assigning the address of newstr to *str is to (1) declare newstr as static, or (2) dynamically allocate newstr (e.g. char *newstr = malloc (sizeof *newstr * strLen + 1);. Then you can assign the value of newstr to str. e.g.:
void replace(char **str, char toReplace, char replaceWith) {
int strLen = strlen(*str);
int i;
char *newstr = malloc (sizeof *newstr * strLen + 1);
if (!newstr) {
fprintf (stderr, "error: virtual memory exhausted.\n");
exit (EXIT_FAILURE);
}
for (i = 0; i < strLen; i++) {
if ((*str)[i] == toReplace)
newstr[i] = replaceWith;
else
newstr[i] = (*str)[i];
}
newstr[strLen] = 0; /* nul-terminate (or use calloc to allocate) */
free (*str); /* MUST have been dynamically allocated in caller */
*str = newstr;
}
(note: str must not have been statically declared in the calling function, and you must free the block of memory it points to or you will create a memory leak by overwriting the starting address to the block of memory it originally pointed to -- making it impossible to free the original block.)
All of these reasons are reasons why it is better to approach this problem by either changing the toReplace and replaceWith characters in place (presuming it str was an array and not a string-literal), or passing an additional array to fill with the replacement as a parameter (or as a pointer to allocate -- or return a pointer to a newly allocated block of memory containing the new string).
Let me know if you have further questions.

Return array in function pointer argument [duplicate]

I want to change the actual argument passed to a function and not a copy of it. For example:
char str[] = "This is a string";
I want to create a function after a call to which the value of str is different. I tried to create a function accepting char** as the argument but I just couldn't get what I want.
I think you mean something like this:
void update_string(char ** ptr)
{
*ptr = strdup("This is a test");
return;
}
Then call the function like this:
char * str = strdup("hello world\n");
printf("%s\n", str);
update_string(&str);
printf("%s\n", str);
You may pass char*. The pointer will be copied, but it will still point to the same string
If you need the pointer itself to be passed (not its copy) you should pass a char**
To change a string passed to a function in-place, use a regular pointer. For example:
void lower_first_char(char *str)
{
*str = tolower(*str);
}
After this function executes, the first character of the passed string will be changed to lowercase.
Pass a char* if you want to modify the actual string:
foo(str);
...
void foo(char *some_string) {
some_string[0] = 'A';
}
str will now hold "Ahis is a string"
If instead of str being an array, you had: char *str = "Hello";, and wanted to modify where str pointed, then you would pass a char**:
bar(&str);
...
void bar(char **ptr_string) {
*ptr_string = "Bye";
}
str will now point to "Bye".

Simple c malloc

this doesn't work:
void function(char* var)
{
var = (char*) malloc (100);
}
int main()
{
char* str;
function(str);
strcpy(str, "some random string");
printf("%s\n", str);
return 0;
}
this does:
void function(char* var)
{
//var = (char*) malloc (100);
}
int main()
{
char* str;
//function(str);
str = (char*) malloc (100);
strcpy(str, "some random string");
printf("%s\n", str);
return 0;
}
Why?
You have to pass the address of the pointer to assign the address you want inside the function, otherwise you are just passing a copy of it:
void function(char** var)
{
*var = malloc (100);
}
int main()
{
char* str;
function(&str);
strcpy(str, "some random string");
printf("%s\n", str);
return 0;
}
You need to use a pointer to pointer as a parameter for that, char **.
When you pass a pointer as a parameter, it gets copied, so what you get inside the function is just another pointer pointing to the same place.
You need to receive a char ** and do:
my_alloc_fun(void **ptr){
*ptr= malloc(size);
}
void *myptr;
my_alloc_fun(&myptr);
This way, you get the address of the pointer inside the function, so that you can make the original pointer to point to the newly allocated memory.
When you call function(str), you are passing the value of str to function. This value is some uninitialized garbage value because you haven't set it to anything in main, but that's not the problem.
The problem is that function has its own pointer, var, into which it puts that garbage value so that one could say var points to the same thing (garbage) that str points to. However, they are not the same variable. They are two distinct variables, and changing var has no effect on str.
When you say var = (char*) malloc (100);, you are allocating memory somewhere and then telling var to point to it. Now var points to a different location than str. Immediately you return from that function, losing var and the location of that memory. This by the way is a memory leak.
When you return back to main, str is as it ever was - pointing to garbage.
A numerical example:
char *str; // str -> 0xfeedface (garbage)
function(str);
// inside 'function', an initialization like this occurs
char *var = str; // var -> 0xfeedface (same garbage)
var = (char*) malloc (100); // var -> 0x12341234 (alloc'd memory)
return;
// back in 'main'
strcpy(str, "some random string"); // str still points to 0xfeedface!
To do this properly, you need to change strs value. This means function needs a pointer to str, or a pointer to a pointer.
void function(char **var)
{
*var = (char*)malloc(sizeof(char) * 100);
}
int main()
{
char *str;
function(&str);
strncpy(str, "some random string", 99);
...
free(str); // important in general
}
Pointers are just like any other variable; the difference is only in what their value represents. Whereas a double has a value that represents a double-precision floating point number, and an int has a value that represents a signed integer, a pointer has a value that represents the location of another variable.
Pointers themselves are still passed by-value to other functions; so your example doesn't work for exactly the same reason that this analagous function doesn't work:
void function(int var)
{
var = 100;
}
int main()
{
int num;
function(num);
printf("%d\n", num);
return 0;
}
The answer in both cases is the same: When function() changes the value of the parameter var, it is changing only its local copy of that - it isn't changing the variable within main().
See my answer to C Programming: malloc() inside another function for an explanation about how to think about this.

Resources