Matheus.M.
Matheus.M.

Reputation: 67

This code is safe of memory leak?

I make a function, this make an operation and after this write on the variable, my question is: this code is safe ?

There is a sample:

#include <stdlib.h>

void test(char **out){
    char *f = (char *) malloc(10);
    f = "123456";
    *out = f;
    return;
}

int main(void){
    char *A = NULL;
    test(&A);
    free(A);
    return;
}

Upvotes: 0

Views: 73

Answers (3)

Angus Comber
Angus Comber

Reputation: 9708

The problem is here:

void test(char **out){
    char *f = (char *) malloc(10);
    f = "123456";
    *out = f;
    return;
}

The malloc line allocates 10 bytes of memory on the heap. So at this stage the address of f will be wherever malloc happened to grab a chunk of memory. For the sake of argument we will say the that this is at 0x10000

Then you assign f the address of a literal string.

The code below prints out what is happening.

#include <stdlib.h>

void test(char **out){
   char *f = (char *) malloc(10);
   printf("f after malloc = %p\n", f);
   f = "123456";
   printf("f after re-assignment = %p\n", f);
   *out = f;
   return;
}

int main(void){
   char *A = NULL;
   test(&A);
   free(A);
   return;
}

Here are some alternative ways to work with strings in C.

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

static  char* b = "test 2"; 

void test2(char **out){
   *out = b;
}

const char* test3(){
   return "test 3";
}

void test4(char **out){
   *out = (char *) malloc(10);
   strcpy(*out, "test 4");
}

int main(void){
   char *A = NULL;
   char *B = NULL;
   char *C = NULL;

   /* Assign A to the address of a 'global' string */
   test2(&A);
   printf("A is now: %s\n", A);
   /* Don't free this */

   /* return a static string */
   B = test3();
   printf("B is now: %s\n", B);

   /* allocate memory on heap and make a copy of data from a source to that memory location */
   test4(&C);
   printf("C is now: %s\n", C);
   free(C);  /* only C is allocated on heap so free this one */
}

Upvotes: 0

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37914

Look more closely into test() definition:

void test(char **out){
    char *f = (char *) malloc(10);
    f = "123456";
    *out = f;
    return;
}

especially those two lines:

char *f = (char *) malloc(10);
f = "123456";

What this code is doing is simply replacing malloc-ed pointer with pointer to string literal, since that you have memory leak in your program (that is, you have lost your original pointer obtained from malloc() call), moreover calling free() (within main()) in this situation is actually undefined behaviour.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59997

It leaks.

Use strcpy for coping the string

Upvotes: 0

Related Questions