-8
char *pear = "";
int f=0;

while(f != 20) {
    pear[f] = 'a';
    f++;
}

So I want to append a's to the char string Why is this causing a buffer problem And I can't use the strcat I have don't like this.

Frank D
  • 1
  • 1

1 Answers1

0

Having a string initialized as

char * pear = "";

prohibits it from being modified. In contrast,

char pear [] = "";

allows you to modify byte 0 (but not subsequent bytes) afterwards without getting an error. However, since the last byte in the string needs to be 0, it is not a good idea to overwrite it.

More importantly, you are trying to give values up to 20th element - you need space for at least 21 elements. Also, be careful with the terminating character - you need the last element in the array to be 0 for it to be a string. Right now it seems that you are just trying to write characters into the array without terminating it properly.

If you don't know the size of your array up front, you can use dynamic memory allocation: malloc, realloc (and don't forget to free at the end).

  • 1
    regarding: char pear [1] = ""; makes it Okay to modify the string afterwards.` that is not true. The variable will contain a NUL byte. However, no more bytes can be set beyond `pear[0]` as any larger offset will result in buffer overflow. Suggest: `char *pear = NULL;` followed, later in the code by something similar to: `pear = malloc( 100 ); if( !pear ) { //handle error }` – user3629249 Dec 22 '17 at 01:24
  • Thank you! I will clarify the answer accordingly. What I meant to say is that char * pear = "" makes it not modifiable at all (const), whereas char pear [1] = "" makes it possible to modify element 0 (which would also screw up the terminal NULL but at least not cause segfaults). – Fadime Bekmambetova Dec 22 '17 at 01:32
  • 1
    `char pear [1] = "";` -> `char pear [] = "";` - Get the compiler to do the work! – Ed Heal Dec 22 '17 at 01:59
  • True true. Lemme fix it. On a side note - I'm debating if I should delete my answer to let Frank D delete the question - cause all the "down'' votes... Because I think my answer might be preventing the question from being deleted. – Fadime Bekmambetova Dec 22 '17 at 16:39