Home > Software engineering >  Can't copy a string to a pointer
Can't copy a string to a pointer

Time:08-08

Hi I'm pretty new to C and still don't have a full understanding of pointers, but essentially I'm trying to copy the result of my encryption to the result pointer, and it keeps throwing various errors, currently a segmentation fault. As far as I understand, since result has been initialised as NULL, it can be changed. Any help is appreciated :)

#include <stdio.h>
#include <stdlib.h>

int pointer copy(char **result){
  char x='password';
  char* p1=&x;
  result=&p1;
  return 0; 
}

int main(void){
char *encrypted_message = NULL;
copy(&encrypted_message);
if(encrypted_message != NULL){
  printf("%s\n", encrypted_message);
  }
free(encrypted_message)
}

CodePudding user response:

You shouldn't leave blanks in the function's name. It can be pointer_copy for example.

And the pointer_copy function doesn't have to return anything so you can leave it void.

You can use strcpy if you still want to use a second pointer in the pointer_copy function. But before, don't forget to allocate memory for the pointer.

Full executable below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void pointer_copy(char **result)
{
    char x[10] = "password";
    char* p1 = malloc(sizeof(char));
    strcpy(p1, x);
    *result = p1;
}

int main(void)
{
    char *encrypted_message = NULL;
    pointer_copy(&encrypted_message);
    if (encrypted_message != NULL){
        printf("%s\n", encrypted_message);
    }
    return 0;
}

Even though you fix the typo, you may still want to get rid of the free(encrypted_message) statement because it gave a SIGTRAP in my compiler and we don't need it at all.

CodePudding user response:

For starters there is a typo

free(encrypted_message)

You forgot to place a semicolon in the end of the statement.

Another typo is in the function name where two words are separated by a space in its declaration. And in the function call there is used another name.

This declaration

char x='password';

does not make a sense. You are trying to initialize an object of the type char with a multibyte character constant that has an implementation-defined value.

It seems you mean

char *x = "password";

Also the function parameter result is a local variable of the function. So its changing is not visible outside the function.

That is the condition of this if statement

if(encrypted_message != NULL)

will always evaluate to false.

And you may call the function free to a pointer that points to a dynamically allocated memory.

Apart from this the return type of the function int also does not make a sense.

It seems you mean the following

#include <stdio.h>

void pointer_copy(char **result){
  char *x = "password";
  *result = x;
}

int main(void){
char *encrypted_message = NULL;
pointer_copy(&encrypted_message);
if(encrypted_message != NULL){
  printf("%s\n", encrypted_message);
  }
}
  • Related