0

Just wondering, because I can't figure out a way to test this. Imagine the scenario whereby I have 10 bytes of memory

  1. I malloc varA with 5 bytes
  2. Assign a string with 7 characters (which use up 8 bytes)
  3. I malloc varB with 5 bytes

Will the program run into an error? Or just end up with gibberish memory?

Does the behaviour varies from a c/c++ and a cuda program?

6
  • 4
    This question is basically "What will my program do if there's a bug in it?". The answer is basically "Probably not what you want or expect. That's why we avoid bugs." Commented Mar 16, 2014 at 9:33
  • 3
    You don't do this! This is not even a possibility. When you have a piece of paper and you write on it, when it's full you don't continue on the desk... or your mom will punish you. Same here! Commented Mar 16, 2014 at 9:34
  • Leaks are when you loose grip of pointers you allocated and did not free. That memory ends up in limbo. Overflows are when you overstep your boundaries writing. Both are deadly: first is a slower death, second not so much. Commented Mar 16, 2014 at 9:36
  • 1
    Haha, I like your comments. I pondered upon this because I was running someone else's source (on cuda) and it gave me serious headache because it worked while such a thing happened. But as you already know, when I continuously run the program... problems.... Commented Mar 16, 2014 at 9:38
  • @springcold Go tell that guy that pointers are not just a starting point of writing. They have a SIZE and you don't overstep it. So it has both a beginning and an ending. Commented Mar 16, 2014 at 9:41

2 Answers 2

7

That's not a memory leak, it's a buffer overflow. And those leads to undefined behavior, which will most likely give you weird problems (or even crashes) during run-time.

Unless you mean point 2 literally, like in

char *str = malloc(5);
str = "foobar";

Then you do have a memory leak, and not a buffer overflow.

Sign up to request clarification or add additional context in comments.

3 Comments

I think that is safe to say that this is undefined behaviour, I don't know if it's equally true the fact that this will cause buffer overflow.
May I ask, will the behaviour likely be the same in Cuda as well?
@springcold The behavior is the same with any C-library.
0

It is an undefined behavior to write beyond allocated memory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.