Solruhama
Solruhama

Reputation: 111

Core dumped while printing

I have the following simple hashing function and I was just playing around the code but found something weird(or I just don't understand what is going on here). so here is code:

/******************************************************************************

                            Online C Compiler.
                Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
uint64_t slash_hash(const char *s)
{
    union { 
        uint64_t h; 
        uint8_t u[8]; 
        
    } uu;
    int i=0; 
    uu.h=strlen(s);
    while (*s) { uu.u[i%8] += *s + i + (*s >> ((uu.h/(i+1)) % 5)); s++; i++; }
    return uu.h; //64-bit
}
int main()
{
    char *p[]={"pole","olep","mamao","omama"};
    int j=0;
    while(*(p+j)){
        printf("%s\n",*(p+j));
        j++;
    };
    for(int i=0;i<4;i++){
        uint64_t var  =  slash_hash(p[i]);
        printf("%lu \n",var);
    }

    return 0;
}

I expected it to print both the stings in the given array and then their hash index, but it only prints:

  1. The stings only and then says cored dumped without printing their hash index.
  2. If I comment out the line that prints the strings, it prints only the hash index without core dumped. I would appreciate it if someone points out what is going on here, as I am new to c, and it is kind of hard to point out the problem by myself.

Upvotes: 0

Views: 56

Answers (1)

selbie
selbie

Reputation: 104559

Your p list is not guaranteed to be null terminated as you have it defined. Hence when j==5, p[5] is undefined and likely has garbage data. Hence while(*p+j)) is undefined behavior.

Instead of this:

char *p[]={"pole","olep","mamao","omama"};
int j=0;
while(*(p+j)){
    printf("%s\n",*(p+j));
    j++;
};

This (with some additinal cleanup for readability):

char *p[]={"pole","olep","mamao","omama", NULL}; // notice the NULL value at the end
int j=0;
while(p[j] != NULL) {
    printf("%s\n",p[j]);
    j++;
};

Upvotes: 1

Related Questions