# malloc help

This topic is 3465 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

[c code] code 1 char *a; a="ahsjsq"; code 2 char*a; a=malloc(6*sizeof(char)); a="ahsjsq"; which is correct : code 1 or code 2 what is the difference between these two codes. do we need to malloc everytime we have to store something in a string ?

##### Share on other sites
Quote:
 Original post by y2jsavechar*a;a = malloc(6*sizeof(char));a = "ahsjsq";

This is wrong. When you assign a string literal to a char* pointer, the system stores that string for you somewhere in your code so that you don't have to allocate memory for it. If you do the code you have above, you set the pointer to the location the compiler came up with for you, and you lose the allocated memory (and therefore you leak that memory). So yeah, the first way is right.

##### Share on other sites
Quote:
 Original post by MJPThis is wrong. When you assign a string literal to a char* pointer, the system stores that string for you somewhere in your code so that you don't have to allocate memory for it. If you do the code you have above, you set the pointer to the location the compiler came up with for you, and you lose the allocated memory (and therefore you leak that memory). So yeah, the first way is right.

-- unless you plan to modify your string, in which case you have to make a copy of your string first:

	char *ptr = "do not modify";	ptr[0] = 'D';  // Run-time error!

#include <string.h>	char *ptr = strdup( "do not modify" );	ptr[0] = 'D';   // Yay!	free( ptr );     // Don't forget to clean up your new string

EDIT:
Un-C++'d it

[Edited by - _fastcall on July 25, 2008 11:11:49 PM]

##### Share on other sites
That should be: "delete[] ptr;" not "delete ptr;".

There's also the builtin function strdup() in string.h, which does the same thing as your make_copy() function but with malloc()/free() instead of new/delete.

##### Share on other sites
String literals are stored somewhere in your executable. When your program is executed, it is loaded into memory first, so these literals already have a place in memory. Whenever you read text from a file or whenever you need to modify a string, then yes, you'll need to allocate sufficient memory for it (and deallocate it when you're done with it).

In C++, you should use std::string (#include <string>), as it takes care of such tedious tasks. In C, you'll have to make do with char pointers and the C string functions (#include "string.h").

##### Share on other sites
Quote:
 Original post by dwahlerThat should be: "delete[] ptr;" not "delete ptr;".There's also the builtin function strdup() in string.h, which does the same thing as your make_copy() function but with malloc()/free() instead of new/delete.

Correct; it should be delete[] in C++, but then again, there isn't a delete in C, I meant to use free ... (C++ habits [smile])