C: mysterious core dump at "printf" -


i wrote simple function creates "cd/dvd" accepts 3 arguments: name, rating, , "boolean" whether cd/dvd ripped or not.

#include <stdio.h>  int makecd(char *name, int rating, int ripped) {     if((rating > 5) || (rating < 0))     {         printf("rating wrong!\n");         return 1;     }      if(ripped = 0)     {         printf("name: %s, rating: %s/5, ripped: false\n", name, rating);         return(0);     }     else if(ripped = 1)     {         printf("name: %s, rating: %s/5, ripped: true\n", name, rating);         return(0);     }     else     {         printf("value of \"ripped\" not set correctly!\n");         return(1);     } }  int main(int argc, char *argv[], char *envp[]) {     makecd("avatar", 4, 1);     /* std::cin.get(); */     char ignore[65536] = {'\0'};     gets(ignore);     return 0; } 

after debugging dbx, found out core dump @ line 18 (just after "if(ripped = 1) { ... }"). mystifies me is, why getting core dump.

the output of dbx follows:

signal segv (no mapping @ fault address) in strlen @ 0xfee8645c 0xfee8645c: strlen+0x000c:      movl     (%eax),%edx current function makecd    18                   printf("name: %s, rating: %s/5, ripped: false\n", name, rating); 

you're using wrong format specifier printf:

printf("name: %s, rating: %s/5, ripped: false\n", name, rating); 

the %s specifier expects address of character array containing null terminated string. first 1 fine, second 1 getting int parameter list. using wrong format specifier invokes undefined behavior, in case manifests crash.

if want print integer, use %d format specifier:

printf("name: %s, rating: %d/5, ripped: false\n", name, rating); 

also, incorrect:

if(ripped = 0) 

this not comparison assignment. comparison, use == operator:

if(ripped == 0) 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -