0

So I need to make a function that takes a parameter of type char **, and makes that point to a string.

I've spent hours on it and I know it's probably a super dumb thing that I'm missing.

Here is my latest attempt:

void magic_string(char ** new_string) {
  char * my_string = (char*) malloc((5+1)*sizeof(char));
  my_string = "abcde";
  new_string = &my_string;
}

But when I try to use the new_string in the calling function, it is still null.

I also tried replacing the last line with *new_string = my_string but recieved a bad access exception.

user13292868
  • 87
  • 1
  • 7
  • There are two major problems here and they are both common FAQ. I have linked a duplicate target per problem. – Lundin Oct 19 '22 at 12:43

2 Answers2

2

The problem is that you're only changing the local variable new_string, so changes aren't reflected in the calling function.

You want to dereference new_string and assign the pointer to that.

*new_string = my_string;

Also, you're leaking memory by first assigning an allocated memory block to my_string, then overwriting that pointer value with a pointer that points to a string literal. You should instead use strcpy:

strcpy(my_string, "abcde");
dbush
  • 205,898
  • 23
  • 218
  • 273
1
  1. my_string = "abcde"; overwrites the value of your pointer, rendering the malloc call redundant. What you want to do is probably use strcpy to copy the string literal into the allocated space instead.
  2. &my_string is a pointer to local memory. So is new_string. Neither is available after the function terminates. Instead, you want to assign the value of my_string to *new_string!
  3. sizeof(char) is by definition 1. No need to multiply by it.
  4. Don’t cast the result of malloc; assign it directly.

The fixed function looks as follows:

void magic_string(char **new_string) {
  char *my_string = malloc(5 + 1);
  strcpy(my_string, "abcde");
  *new_string = my_string;
}

And it needs to be called with a pointer, e.g.:

char *str;
magic_string(&str);
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Thanks so much! Super helpful :) Can I just ask in the last calling section why it is called with ```char *str``` and not ```char **str```? – user13292868 Oct 19 '22 at 12:20
  • 1
    @user13292868 If you declare `str` as `char**` and call your function as `magic_string(str)`, you are passing an *uninitialised pointer* into your function, and then you are dereferencing that uninitialised pointer (when you execute `*new_string`). That’s illegal. By contrast, in the code I’ve posted, `str` is a local variable so `&str` is a well-defined, initialised pointer to that automatic (stack-allocated) variable, and `*new_string` is dereferencing the pointer, i.e. referring to that stack-allocated variable. – Konrad Rudolph Oct 19 '22 at 12:22