Search code examples
cstringpointersstring-literals

I want to know why this works without having to bind memory for the string


Hello guys I recently picked up C programming and I am stuck at understanding pointers. As far as I understand to store a value in a pointer you have to bind memory (using malloc) the size of the value you want to store. Given this, the following code should not work as I have not allocated 11 bytes of memory to store my string of size 11 bytes and yet for some reason beyond my comprehension it works perfectly fine.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){

  char *str = NULL;

  str = "hello world\0";
  printf("filename = %s\n", str);
  return 0;
}

Solution

  • When you declare a string literal in a C program, it is stored in a read-only section of the program code. A statement of the form char *str = "hello"; will assign the address of this string to the char* pointer. However, the string itself (i.e., the characters h, e, l, l and o, plus the \0 string terminator) are still located in read-only memory, so you can't change them at all.

    Note that there's no need for you to explicitly add a zero byte terminator to your string declarations. The C compiler will do this for you.