Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this generate a memory leak?

void aFunction_2()
{
    char* c = new char[10];
    c = "abcefgh";
}

Questions:

  1. Will the: c = "abdefgh" be stored in the new char[10]?

  2. If the c = "abcdefgh" is another memory area should I dealloc it?

  3. If I wanted to save info into the char[10] would I use a function like strcpy to put the info into the char[10]?

like image 575
okami Avatar asked Dec 09 '22 14:12

okami


2 Answers

Yes that is a memory leak.

Yes, you would use strcpy to put a string into an allocated char array.

Since this is C++ code you would do neither one though. You would use std::string.

like image 110
Zan Lynx Avatar answered Dec 12 '22 03:12

Zan Lynx


void aFunction_2()
{
    char* c = new char[10]; //OK
    c = "abcefgh";          //Error, use strcpy or preferably use std::string
}

1- Will the: c = "abdefgh" be allocated inner the new char[10]?

no, you are changing the pointer from previously pointing to a memory location of 10 bytes to point to the new constant string causing a memory leak of ten bytes.

2- If the c = "abcdefgh" is another memory area should I dealloc it?

no, it hasn't been allocated on heap, its in read-only memory

3- If I wanted to save info inner the char[10] I would use a function like strcpy to put the info inner the char[10]?

not sure what you mean with 'inner' here. when you allocate using new the memory is allocated in the heap and in normal circumstances can be accessed from any part of your program if you provide the pointer to the memory block.

like image 29
AndersK Avatar answered Dec 12 '22 05:12

AndersK