1

I have been trying to understand what is malloc() and why is it used. I understand that malloc is for dynamic allocation of memory, it is needed if you don't know how much memory you wan't to create. I have been doing some hands-on on it.

The following code declares an array of character pointers, and 1st character pointer is initialized with "hello". This works fine.

int main()
{


char *strarray[5];
strarray[0]="hello";
printf("%s\n",strarray[0]);
return 0;
}

But if i try to use strcpy() function to copy "hello" string into strarray[0] (without malloc()) it gives a problem. And it goes into some loop and does not copy the string. And it works fine if i use malloc to allocate memory.

int main()
{

char *strarray[5];
//strarray[0]=(char *)malloc(sizeof(char)*10);
strcpy(strarray[0],"hello");
printf("%s\n",strarray[0]);
return 0;
}

I want to know what makes the difference? If i can initialize "hello" to a char pointer for which malloc is not used, why can't i do the same with strcpy().

Jim
  • 1,056
  • 1
  • 13
  • 19
Ravindra
  • 59
  • 1
  • 10
  • You have a text file on disk that has data you need in an array of strings. One word per string. When finished your array should contain N strings, where N is the number of words in the file... And it has to work for *any* size file. Think about how you can *not* code that with fixed-length arrays, then ask yourself what is the *memory allocation* function `malloc()` good for. – WhozCraig Sep 13 '13 at 20:22

3 Answers3

2
char *strarray[5];

will allocate array of five pointers to the characters (which can be interpreted as strings).

What this will not allocate is the memory space to place these five strings to. So, if you want to make all pointers to point to the different strings, you need to allocate them yourself.

However, as these are pointers, you don't really need to allocate anything, if you don't want to. That is why your first example is working. strarray[0]="hello"; will make the first element of the array to point to the location where "hello" string literal is stored (the compiler will put this literal somewhere in the memory for you, so your pointer will point to the valid memory location).

To sum up, in the first example, your pointer is pointing to the memory already allocated and initialized with "hello" (compiler did this for you) - you're not copying the string, you're just assigning value to the pointer. In the second example your pointer is pointing to some undefined location, which you didn't explicitly reserved, but you're trying to write into it.

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
  • Sorry for misguiding by using array of five pointers. The question applies even for one character pointer. And i am actually using only one pointer. I want to copy some string to this character pointer which is not allocated memory using malloc. If I can do this just by initializing (with out malloc), Then why can't I use strcpy with out using malloc() is my question. – Ravindra Sep 13 '13 at 20:21
  • @Ravindra actually, you can just ignore array in the answer, as it is concentrated on a single pointer. I've added the last paragraph that should make sense. – Nemanja Boric Sep 13 '13 at 20:22
  • That's where i got confused. Pointing to some already allocated memory, and copying to some pointer which is pointing to undefined location! Now i have little clarity about what's going on. Thanks :) – Ravindra Sep 13 '13 at 20:35
2

This is wrong: char *strarray[5]; This is stack-allocating 5 char* pointers. I think you wanted to write char strarray[6], which creates 6 chars on the stack. That can accommodate "hello" and its implicit NULL-terminator (the NULL terminator tells C functions that a string has ended).

Having written char strarray[6];, strcpy(strarray, "hello"); is safe. Then you can call:

printf("%s\n",strarray);

where I have dropped the [0]: the %s expects a char* not a char: strarray[0] is a char type.

You use malloc to allocate memory on the heap. Might I suggest you read Kernighan and Ritchie (C Programming Language) for more details on that?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Forget about array of character pointers. let us say i have only one character pointer like bellow. char *strarray; /*strarray[0]=(char *)malloc(sizeof(char)*10);*/ strcpy(strarray,"hello"); printf("%s\n",strarray); still it doesn't work – Ravindra Sep 13 '13 at 20:23
  • @Ravindra; I can't tell where // ends!, but as a starter, remove [0] from your printf as %s expects a char* not a char. See the extra text in my answer. – Bathsheba Sep 13 '13 at 20:25
  • changed it. Now you can get. That comment is just to show the diff b/w "if" and "if not" i use malloc(). – Ravindra Sep 13 '13 at 20:28
  • Kernighan and ritchie, sure! Thank you. – Ravindra Sep 13 '13 at 20:39
  • @Ravinda pleasure; read the first chapter, do the exercises and I look forward to reading your answers on so! – Bathsheba Sep 13 '13 at 20:55
0

malloc(): Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

void* malloc (size_t size);  

size_t is an unsigned int type.

it is needed if you don't know how much memory you wan't to create,this is not correct.
you should know how much minimum memory required.

with the help of malloc() you can allocating memory at run time not at compile time.

strarray[0]="hello";   
//here you need not to allocate memory as this is an assignment 

You need to allocate some space before using a pointer as destination string in strcpy()

strcpy() Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

for this you need to allocate Memory first.

strcpy itself doesn't allocate memory for the destination string

Gangadhar
  • 10,248
  • 3
  • 31
  • 50
  • I meant "you don't know how much memory you want to create in compile time" – Ravindra Sep 13 '13 at 20:24
  • @Ravindra Just please try to understand this one.You should required to know how much memory is enough to hold the respected content.based on that you can allocate memory .that can be static(compile time) or else dynamic(run time). malloc main purpose is when you do not how many members of that much size are required. for static allocation you cannot increase or decrease size but you can with dynamic you can. – Gangadhar Sep 13 '13 at 20:48