Code:
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char* test= "hello there";
char** temp = (char**) malloc(sizeof(char*) * 1);
temp[0] = (char*) malloc(sizeof(char)* 20);
strcpy(temp[0],test);
printf("'%s'\n",temp[0]);
free(temp[0]);
free(temp);
getchar();
}
I believe you're allocating the wrong amount of memory, however, since char * and char ** are the same in your case, you shouldn't experience any problems for the first allocation. The second allocation is very different. You were allocating 4 times as much memory by allocating 20 char *'s when you should have been allocating 20 chars.
Take care to understand what you are malloc()ing. This is why the FAQ on malloc() refers to using a format similar to this:
Code:
int *p;
...
p = malloc(sizeof(*p));
If you're using a C89 compiler, you probably casted malloc() to make the compiler shut up about the error, when the reason for the error was that you forgot to include stdlib.h. On a C99 compiler, you can't get away with that.