0

I try to understand why my simple code who use bzero or memset cause a bus error with clangor gcc I find no logical explication.

I try the simple example from this post : Proper way to empty a C-String

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

int main() {
    char *str;
    printf("%lu\n",strlen(str));
    bzero(str,1); // ok
    str = "bonjour";
    bzero(str,strlen(str)); // bus error
    // memset(str, 0, strlen(str)); // bus error
    return(0);
}
Knupel
  • 323
  • 2
  • 14
  • `str` is a pointer to a string literal, those can't be changed, use `char str[8]`, `strlen(str)` is also bad as `str` is uninitialized. – anastaciu Sep 23 '20 at 13:41
  • `char *str` is an uninistailized pointer. You're just doing operations on random memory. This is not good. Instead do `char str[8];` or so. – JHBonarius Sep 23 '20 at 13:42
  • I picked two duplicates, one for each bug mentioned in the comments above. – Lundin Sep 23 '20 at 13:45
  • 1
    `str = "bonjour";` shouldn't work. https://stackoverflow.com/a/11864462 – JHBonarius Sep 23 '20 at 13:46
  • So the usual order of study C would be: arrays, then pointers, then strings. Not the other way around. – Lundin Sep 23 '20 at 13:48
  • 1
    @JHBonarius, it's a valid statement, it assigns the string literal to `str` pointer, it just doesn't work as the OP would expect. It should be `const` qualified precisely to avoid what the OP is trying to do. – anastaciu Sep 23 '20 at 13:51
  • @Lundin - unless you're taking CS50 :-) – Steve Friedl Sep 23 '20 at 13:52
  • 1
    @SteveFriedl, that's one of those things that should be uninvented :) – anastaciu Sep 23 '20 at 13:56
  • @JHBonarius and @anastaciu thx I solve the problem with an strcpy() for the moment. The thing me in the wrong when I wrote `str = "bonjour ` when I use `printf`the terminal write `bonjour`So i thought my code is ok, but not :( thx at all. – Knupel Sep 23 '20 at 14:02
  • 1
    @anastaciu I was using a C++ compiler. that's probably why it wasn't working for me ;) – JHBonarius Sep 23 '20 at 14:05
  • @JHBonarius, yes, in C++ non-const qualified string literals are forbidden, thankfully. Though gcc and clang only issue warnings because of the C99 extensions, sadly. – anastaciu Sep 23 '20 at 14:09
  • @SteveFriedl In that case it they teach you to become a lost cause, so it won't matter. – Lundin Sep 23 '20 at 14:32

0 Answers0