alketii / violetland

Automatically exported from code.google.com/p/violetland
0 stars 0 forks source link

incorrect memory operations #24

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
In the r181:

LifeForm::LifeForm(float x, float y, int w, int h) :
    Object(x, y, w, h) {
    char *buf;
    sprintf(buf = new char[30], "%010li-%010li", (rand() % 9999999999),
            static_cast<long int> (time(NULL)));
    fprintf(stdout, "%s\n", buf);
    Id = buf;
    delete[] buf;

...

}

Do not delete buf until this memory chunk used in Id.

Original issue reported on code.google.com by intergal...@gmail.com on 6 Feb 2010 at 11:50

GoogleCodeExporter commented 9 years ago
on't sure if this operation is incorrect.

For me this code worked on linux, windows and for many others users on various
systems too without any errors or broken behavior.

I couldn't google clear information about how string is processing assignment 
of char*.

But I has executed now following sample (compiled with VS2008):

char* c = new char[10];
sprintf(c, "%s", "foo");
std::string s = c;
delete[] c;
c = new char[10];
sprintf(c, "%s", "bar");
fprintf(stdout, "%s\n", s.c_str());
fprintf(stdout, "%s\n", c);
delete[] c;
fprintf(stdout, "%s\n", s.c_str());
fprintf(stdout, "%s\n", c);

It said:

foo
bar
foo
▌▌▌▌▌▌▌▌▌▌▌▌▌▌

Original comment by 5253...@gmail.com on 12 Feb 2010 at 10:09

GoogleCodeExporter commented 9 years ago
Ah, no, I has understand.

Probably I shouldn't use C-strings at all (especially new ... sprintf ... delete
constructions).

Original comment by 5253...@gmail.com on 12 Feb 2010 at 10:55

GoogleCodeExporter commented 9 years ago

Original comment by 5253...@gmail.com on 12 Feb 2010 at 10:56

GoogleCodeExporter commented 9 years ago

Original comment by 5253...@gmail.com on 13 Feb 2010 at 10:42