0

I am brand new to C. I am trying to make sure I understand dynamic memory allocation so I was coming up with examples on my own. When I stumbled on this I was not sure why this crashes. That is, I don't see what we have violated. Maybe one of the advanced C programmers here can explain to me. Can we not manipulate a string after we point it somewhere? Thanks in advance.

int main(){

char *name = (char*)malloc(sizeof(char)*10);
name = "Hello";
name[0] = 'X'; //<------ bad idea?
puts(name); 
free(name);

char aname[sizeof(char)*10] = "Hello";
aname[0] = 'X';
puts(aname); 



return 0;
}
luk32
  • 15,812
  • 38
  • 62
Rob L
  • 3,073
  • 6
  • 31
  • 61

3 Answers3

6

Because it's all wrong.

First, don't cast the return value of malloc() in C. Also don't scale character allocations by sizeof(char), that's just a complicated way of typing 1 and of course x * 1 is still just x so why not cut to the chase.

Second, C doesn't support direct array assignment, and there is no real support for strings.

Third, literal strings cannot be modified.

When you do this:

name = "Hello";  // Very bad idea, after malloc().
name[0] = 'X';   // Very bad idea, tries to modify the literal string.

you overwrite the pointer returned by malloc() with a different pointer, namely the address of a constant string stored somewhere. You then try to change the first character of that constant string, which is not allowed.

It should be:

name = malloc(10);
snprintf(name, 10, "Hello");
name[0] = 'X';  // Perfectly fine, happens in memory from malloc().

This actually uses the memory you allocated, which makes whatever modifications you want to do after copying the string into the memory just as valid.

You might also want to check that malloc() doesn't fail, in which case name will be NULL.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
1

There is good explanation available for all problem in your code, click here.

working code:

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

int main(){

char *name = malloc(sizeof(char)*10);
if(name == NULL) {
    printf("Error allocating memory\n");
    return -1;
}
strcpy(name,"Hello");
name[0] = 'X'; 
puts(name); 
free(name);

char aname[sizeof(char)*10] = "Hello";
aname[0] = 'X';
puts(aname); 
return 0;

}
Community
  • 1
  • 1
sujin
  • 2,813
  • 2
  • 21
  • 33
0

You are trying to change string, and string is stored as literal in modern compilers. If you want to change string, use array instead.

String will stored as literal, but as it is char array, it will store separate chars on stack.

char arr[]= "Hello"; //Hello is stored as literal.

But arr[0] will have 'H'..

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137