Thursday, June 20, 2019

Allocate memory and save string in c

I was wondering why the following code isnt't working



int main(int argc, char **argv)
{
char *test = (char*) malloc(12*sizeof(char));
test = "testingonly";
free(test);
}


After thinking about it my assumption was that first i allocate space for 12 chars in memory but the assignment in the next line creates a char array on the stack and the memory address of that is passed to test. So free() tries to release space on the stack which is not allowed. Is that correct?



So what would be the correct approach to save a string on the heap? Is the following a common way?



int main(int argc, char **argv)
{
char *test = (char*) malloc(12*sizeof(char));
strcpy(test, "testingonly");
free(test);
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...