-3

I have a function which receive a pointer of char array as an argument(char** messageErreur). That pointer is created in the main, but no memory is allocated, as it is created only if necessary (error message to display) (no choice here, the method comes from an unchangeable .h file).

here is the code where I get segmentation fault:

imageMsgErr (messageErreur, "error message");
printf("erreur1 P2\n");
printf("message erreur %s\n", *messageErreur); //**where i get the seg fault


void imageMsgErr (char** messageErreur, char* msg){

    messageErreur= (char**)malloc(sizeof(char*));
    messageErreur[0]= (char*)malloc(sizeof (char) * 100);

    if (*messageErreur){
        printf("before strcpy\n");
        strcpy(*messageErreur, msg);
        printf("message erreur %s\n", *messageErreur);
    }
    return;

I have tried several similar code with the same result: segmentation fault when it execute the line:

printf("message erreur %s\n", *messageErreur);
syntonym
  • 7,134
  • 2
  • 32
  • 45
  • Why are you casting the return values from `malloc`? – Ed Heal Jul 16 '16 at 20:44
  • Compile your code with the `-g` flag, run `valgrind` on your program with the `--leak-check=full` option and include its output in your question. – Filip Allberg Jul 16 '16 at 20:45
  • You probably should read this: http://stackoverflow.com/questions/2838038/c-programming-malloc-inside-another-function/2838207#2838207 – jamesdlin Jul 16 '16 at 20:53
  • You're doing weird shit in there. A) you're assigning to a local copy, which means those assignments have no effect outside of the function and only serve to leak memory before you segfault on your original (probably garbage) value B) what is the point of a a dynamic array of size 1? You're effectively just `strdup`ing the msg. So why notcut the array-of-size-1 middleman and do just that -- `char* messageErreur = strdup(msg);` ? – Petr Skocik Jul 16 '16 at 21:02

1 Answers1

0

The line

messageErreur= (char**)malloc(sizeof(char*));

changes where messageErreur points locally, only in the function. It does not change where the corresponding variable in the calling function points to.

One easy way to fix it is to change the function slightly.

char** imageMsgErr (char* msg)
{
   char** messageErreur = malloc(sizeof(char*));
   messageErreur[0]= malloc(sizeof (char) * 100);

   if (*messageErreur){
      printf("before strcpy\n");
      strcpy(*messageErreur, msg);
      printf("message erreur %s\n", *messageErreur);
   }
   return messageErreur;
}

and change the call to:

messageErreur = imageMsgErr("error message");

PS

See Do I cast the result of malloc?

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270