简体   繁体   中英

freeing an double pointer

int size_of_daten = 5;
char *data[size_of_daten];
char *normal_Pointer = (char*)malloc(sizeof(char) * 100);
int i;

for(i=0; i<size_of_daten; i++) {
    data[i] = (char*)malloc(sizeof(char) * 100);
}

data[0] = "0";
data[1] = "1";
data[2] = "2";
data[3] = "3";
data[4] = "4";

printf("data[2] %s\n",data[2]);

strcpy(normal_Pointer,data[2]);

for(i=0; i<size_of_daten; i++) {
   free(data[i]);
}

free(data);

I just tried this... even I freed the array as I malloced it... also I copied the value of data[2] and didn't point at it... so that shouldn't be the problem...

You're trying to copy the strings "0" , "1" , etc. into your data array: you can't just use = to copy strings, you'll need to use a string library method like strcpy .

Once you assign to your array elements those literal strings, eg: data[0]= "0"; , the array elements no longer point to the memory that you've allocated, they point to memory that doesn't belong to you, and you can't use free . You've lost the references to your memory blocks from malloc , causing a memory leak.

Furthermore, you can't do free(data); because it wasn't allocated using malloc : it's an array allocated on the stack.

This is not how you copy data into an array of char s you've previously allocated:

data[0]= "0";
data[1]= "1";
data[2]= "2";
data[3]= "3";
data[4]= "4";

You're overwriting the pointers with the address of 5 new pointers. At this point you've lost the address of the memory you had allocated, and when you call free you're calling it on the statically allocated string "0" .

You need to use strcpy to copy bytes from one character array into another:

strcpy(dest[0], "0");
strcpy(dest[1], "1");
/* etc */

With data[0]= "0" you are overwriting whatever malloced address returned by malloc . What you should be doing instead is

strcpy(data[0], "0");
strcpy(data[1], "1");
...

First, assignment to the elements of data after allocating leaks the previously allocated memory. When you assign a char *, you assign only the char *: it doesn't copy the string, it overwrites the pointer.

Second, you're freeing data declared on the stack. You define data with:

char *data[size_of_daten];

This describes an on-stack array of character pointers. It will go out of scope when your function returns, and freeing it manually will blow up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM