Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits; reviewed

...

At compile time, string literals are used to create an array of static storage duration of sufficient length to contain the character sequence and a terminating null character. It is unspecified whether these arrays of string literals are distinct from each other. The behavior is undefined if a program attempts to modify any string literals. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory . See (see undefined behavior 33.)

String literals are usually referred to via by a pointer to, or array of characters. Ideally, they should be assigned only to pointers to (or arrays of) const char.

...

Do not attempt to modify a string literal. Instead, use a named array of characters to create a modifiable copy of a string literal.

This rule is an a specific instance of EXP40-C. Do not modify constant objects.

...

Code Block
bgColor#FFcccc
langc
#include <stdio.h>
#include <string.h>
 
const char *get_dirname(const char *pathname) {
  char *slash;
  slash = strrchr(pathname, '/');
  if (slash) {
    *slash = '\0'; /* Undefined behavior */
  }
  return pathname;
}

int main(void) {
  puts(get_dirname(__FILE__));
  return 0;
}

...

Code Block
bgColor#ccccff
langc
#include <stddef.h>
#include <stdio.h>
#include <string.h>
 
char *get_dirname(const char *pathname, char *dirname, size_t size) {
  const char *slash;
  slash = strrchr(pathname, '/');
  if (slash) {
    ptrdiff_t slash_idx = slash - pathname;
    if ((size_t)slash_idx <= size) {
      memcpy(dirname, pathname, slash_idx);
      dirname[slash_idx] = '\0';      
      return dirname;
    }
  }
  return 0;
}
 
int main(void) {
  char dirname[260];
  if (get_dirname(__FILE__, dirname, sizeof(dirname))) {
    puts(dirname);
  }
  return 0;
}

...