Ad
  • Custom User Avatar

    Putting the string on the heap is important since we need writable memory. If you were to use so-called VLAs (e.g., a string allocated on the stack you could get non-writable memory). In C stack-allocated strings should be considered immutable.

    ?!

    You can absolutely have mutable strings on the stack. char buf[11]; would work just fine for both your solutions.

    Seems like you got pointers and arrays confused. A pointer to a string literal (stored in the data segment) is not a "stack-allocated string". There's a significant difference between const char *foo = "bar"; and char foo[] = "bar";.

    VLAs don't particularly factor into this, but they are absolutely mutable (seeing as they cannot be initialized, they would be useless otherwise). There is no such thing as "could" when dealing with well defined behaviours.

  • Custom User Avatar

    I think that making it static would not be a good idea.
    Putting the string on the heap is important since we need writable memory. If you were to use so-called VLAs (e.g., a string allocated on the stack you could get non-writable memory). In C stack-allocated strings should be considered immutable.
    Thus, going with malloc/calloc is a good idea here. Also freeing usually is implemented to be almost constant time, so there's no need to worry about that.
    I hope I didn't misunderstand what you meant by static :'D

  • Custom User Avatar

    I've been doing garbage collected languages too much. I'd probably make it static rather than just adding a free for performance.

  • Default User Avatar

    this will leak memory if buf is not freed

  • Custom User Avatar

    I personally have no idea of what you mean, please alaborate and I'll include it in the description :smile:

  • Custom User Avatar

    Just! I didn't pay attention. Thanks

  • Default User Avatar

    did you declare sum to be of type double for a reason?

  • Default User Avatar

    I think for the bash case it may be worth mentioning standard unix tools.

  • Default User Avatar

    Shouldn't the input/output types be std::vector<int> rather than int[]?